Một quan sát cho phép bạn chỉ đăng ký trong khi một chủ đề cho phép bạn cả xuất bản và đăng ký.
Vì vậy, một chủ đề cho phép các dịch vụ của bạn được sử dụng làm nhà xuất bản và người đăng ký.
Đến bây giờ, tôi không giỏi lắm Observablenên tôi chỉ chia sẻ một ví dụ về Subject.
Hãy hiểu rõ hơn với một ví dụ CLI góc . Chạy các lệnh dưới đây:
npm install -g @angular/cli
ng new angular2-subject
cd angular2-subject
ng serve
Thay thế nội dung của app.component.htmlbằng:
<div *ngIf="message">
{{message}}
</div>
<app-home>
</app-home>
Chạy lệnh ng g c components/homeđể tạo thành phần nhà. Thay thế nội dung của home.component.htmlbằng:
<input type="text" placeholder="Enter message" #message>
<button type="button" (click)="setMessage(message)" >Send message</button>
#messagelà biến cục bộ ở đây. Thêm một tài sản message: string;
cho app.component.tslớp của.
Chạy lệnh này ng g s service/message. Điều này sẽ tạo ra một dịch vụ tại src\app\service\message.service.ts. Cung cấp dịch vụ này cho ứng dụng .
Nhập Subjectvào MessageService. Thêm một chủ đề quá. Mã cuối cùng sẽ trông như thế này:
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class MessageService {
public message = new Subject<string>();
setMessage(value: string) {
this.message.next(value); //it is publishing this value to all the subscribers that have already subscribed to this message
}
}
Bây giờ, đưa dịch vụ này vào home.component.tsvà chuyển một thể hiện của nó cho hàm tạo. Làm điều này cho app.component.tsquá. Sử dụng ví dụ dịch vụ này để truyền giá trị của #messagehàm dịch vụ setMessage:
import { Component } from '@angular/core';
import { MessageService } from '../../service/message.service';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent {
constructor(public messageService:MessageService) { }
setMessage(event) {
console.log(event.value);
this.messageService.setMessage(event.value);
}
}
Bên trong app.component.ts, đăng ký và hủy đăng ký (để tránh rò rỉ bộ nhớ) vào Subject:
import { Component, OnDestroy } from '@angular/core';
import { MessageService } from './service/message.service';
import { Subscription } from 'rxjs/Subscription';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
message: string;
subscription: Subscription;
constructor(public messageService: MessageService) { }
ngOnInit() {
this.subscription = this.messageService.message.subscribe(
(message) => {
this.message = message;
}
);
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
Đó là nó.
Bây giờ, bất kỳ giá trị nhập vào bên trong #messagecủa home.component.htmlsẽ được in để {{message}}bên trongapp.component.html