[英]Angular 4 Components communication With RxJs
我正在关注本教程。 与App-component一起正常接收消息,但不适用于其他组件。 我在@ngModule中将MessageService用作整个应用程序范围进行注入。 Appcomponent接收消息,但其他组件可以发送msgs而不接收消息。
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class MessageService {
private subject = new Subject<any>();
sendMessage(message: string) {
this.subject.next({ text: message });
console.log('called:' + message);
}
clearMessage() {
this.subject.next();
}
getMessage(): Observable<any> {
console.log('message geting');
return this.subject.asObservable();
}
}
2)LoginComponent //用于发送消息
import { Observable } from 'rxjs/Observable';
import { MessageService } from '../services/message.service';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
constructor(
private messageservice ?:MessageService
) {
sendMessage(): void {
console.log("send");
this.messageservice.sendMessage('Message from waqas to login');
}
clearMessage(): void {
// clear message
this.messageservice.clearMessage();
}
3)TestComponent //测试接收消息
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
import { MessageService } from '../services/index';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css'],
})
export class TestComponent implements OnDestroy {
ngOnDestroy(): void {
this.subscription.unsubscribe();
}
// title = 'app';
message: any;
subscription: Subscription;
constructor(private messageService: MessageService) {
// subscribe to home component messages
this.subscription = this.messageService.getMessage().subscribe(message => { this.message = message;console.log(message) });
// console.log('receving'+this.message);
}
}
AppModule文件
providers: [MessageService,UserService,AuthenticationService,UploadFileService,CategoryService,ProductService,AuthGuard,AdminAuthGuard,
{provide: ErrorHandler, useClass: AppErrorHandler},
{
provide: HTTP_INTERCEPTORS,
useClass: TokenInterceptor,
multi: true
}
],
bootstrap: [AppComponent],
})
我不知道如何更改TestComponent或LoginComponent的引导程序提供程序以使用MessageService。 我也通过stackoverflow谷歌搜索和其他问题,但不能解决我的问题。
提前致谢
我认为您的问题是概念性的。 您期望能够通过MessageService有效地将消息从LoginComponent发送到TestComponent。
但是,由于您显然将这两个组件都用作顶级(可路由)组件,并且它们在视图层次结构中都不存在,因此在同一时间点仅存在其中一个。
因此,当您的LoginComponent发送消息时,TestComponent并不在那里可以接收它-在MessageService已经发出消息之后,它订阅了MessageService。
一种可能的解决方法是使MessageService的Observable成为BehaviorSubject而不是Subject。
不同之处在于BehaviorSubject将始终在订阅时发出最后一条消息。 这可能适合您的用例,也可能不适合。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.