import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class MessageService {
private subject = new Subject<any>();
logout() {
this.subject.next({ text: 'logout'});
}
getMessage(): Observable<any> {
return this.subject.asObservable();
}
}
在标题组件中:
import { Component } from '@angular/core';
import { MessageService} from 'service/MessageService'; //import service here as per your directory
@Component({
selector: 'layout-header',
templateUrl: './header.component.html'
})
export class HeaderComponent {
constructor(private messageService: MessageService) {}
clickLogout(): void {
// send message to subscribers via observable subject
this.messageService.logout();
}
}
编辑
import { Component } from '@angular/core';
import { Subscription } from 'rxjs/Subscription'; //Edit
import { MessageService} from 'service/MessageService'; //import service here as per your directory
@Component({
selector: 'another-component',
templateUrl: './another.component.html'
})
export class AnotherComponent {
constructor(private messageService: MessageService) {
// subscribe to home component messages
this.messageService.getMessage().subscribe(message => {
//do your logout stuff here
});
}
ngOnDestroy() {
// unsubscribe to ensure no memory leaks
this.subscription.unsubscribe();
}
}
引用自
here
.