已排序 2 个组件之间的 Angular 6 通信服务



嗨,伙计们,我正在努力使用 Angular 6 及其组件,我创建了一个服务来传达一个组件中触发的事件,并在它发生时重新加载另一个组件。

服务的代码是:

import { Injectable } from '@angular/core';
import { Observable, BehaviorSubject} from 'rxjs';
@Injectable()
export class CommunicationService {
private subject = new BehaviorSubject<boolean>(false);
constructor() { }
public change(){
this.subject.next(true);
}
public getChange(): Observable<boolean>{
return this.subject.asObservable();
}
}

然后是可观察组件代码:

public subscription: Subscription;
constructor(
private _router: Router,
private _communication: CommunicationService
){}
loginUser()
{
this._router.navigate(['./loginUser']);
this.subscription= Observable.interval(500).subscribe(x=> 
{
this._communication.getChange().subscribe( resp=>{
if(resp===true){
this.ngOnInit();
this.subscription.unsubscribe();
}
})
});
}

和触发器组件代码:

this._communication.change();

基本上 las 组件导入通信服务并调用方法 change(( 我正在对代码进行解码,它似乎做得很好,但我在订阅的响应中总是出错,即使调用了更改的方法,我做错了什么?

更新排序 我的第一个代码是正确的,问题是在提供程序中的两个组件中导入服务,而不是在应用程序模块中导入它。伊特的工作很好

在服务中

private subject= new BehaviorSubject(false);
curretSubject = this.subject.asObservable();
constructor() { }
public changeSubject(fl: boolean) {
this.subject.next(fl)
}

元件:

loginUser()
{
this._router.navigate(['./loginUser']);
this.subscription= Observable.interval(500).subscribe(x=> 
{
this._communication.curretSubject.subscribe( resp=>{
if(resp===true){
this.ngOnInit();
this.subscription.unsubscribe();
}
})
});
}

触发:

this._communication.changeSubject(true);

经过一些更改后,代码是这样的:

服务:

private subject= new BehaviorSubject(false);
currentSubject = this.subject.asObservable();
constructor() { }
public change(fl: boolean) {
this.subject.next(fl);
}

反转为 0,5 的分量侦听:

loginUser()
{
this._router.navigate(['./loginUser']);
this.subscription= Observable.interval(500).subscribe(x => {
this._communication.currentSubject.subscribe( resp => {
if(resp===true){
this.ngOnInit();
this.subscription.unsubscribe();
}
})
});

}

触发:

public onSubmit(){
this._userService.signup(this.userAux, 'true').subscribe(
resp2 => {
this.token = resp2.token;
if (this.token.length <= 0) {
alert('El token no se ha generado');
} else {
localStorage.setItem('token', this.token);
this._communication.change(true);
this._router.navigate(['./']);
}
},
err => {
const errorMessage = <any>err;
if (errorMessage != null) {
const body = JSON.parse(err._body);
this.errorMessage = body.message;
}
}
}

响应都是假的,执行流程是首先 loginUser(( 每 0,5 秒继续侦听一次订阅可观察对象,然后组件触发器调用 change(( 之后 Observable.interval 继续侦听但值为 false

最新更新