1.Angular 2 RxJS Subject 应用
message.service.ts
import { Injectable } from '@angular/core';
import {Observable} from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class MessageService {
private subject = new Subject<any>();
sendMessage(message: string) {
this.subject.next({ text: message });
}
clearMessage() {
this.subject.next();
}
getMessage(): Observable<any> {
return this.subject.asObservable();
}
}
home.component.ts
import { Component } from '@angular/core';
import { MessageService } from '../_services/index';
@Component({
moduleId: module.id,
templateUrl: 'home.component.html'
})
export class HomeComponent {
constructor(private messageService: MessageService) {}
sendMessage(): void { // 发送消息
this.messageService.sendMessage('Message from Home Component to App Component!');
}
clearMessage(): void { // 清除消息
this.messageService.clearMessage();
}
}
app.component.ts
import { Component, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { MessageService } from './_services/index';
@Component({
moduleId: module.id,
selector: 'app',
templateUrl: 'app.component.html'
})
export class AppComponent implements OnDestroy {
message: any;
subscription: Subscription;
constructor(private messageService: MessageService) {
this.subscription = this.messageService.getMessage()
.subscribe(message => { this.message = message; });
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
- 使用BehaviorSubject
private testSubjcst = new BehaviorSubject<any>('');
private testObservable = this.testSubjcst.asObservable();
ngInit(){
this.testSubjcst.next('1,2,2,3,4,5,5,6,47');
this.testObservable.subscribe(next => {
console.log(next);
});
}
网友评论