嗨,伙计们,我在角形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组件导入了Communication并调用了方法change(),我正在删除代码,并且它似乎做得很好,但是我总是在订阅的响应中出现错误,即使方法更改被调用,我做错了什么?
更新排序我的第一段代码是对的,问题是在提供者的两个组件中导入服务,而不是在app模块中导入它。艾伯特的作品很好
发布于 2018-10-19 13:57:47
在服役中
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);发布于 2018-10-19 17:16:51
经过几次修改后,代码如下所示:
服务:
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秒继续侦听可观察到的对象,然后组件触发器调用Observable.interval ()之后继续侦听,但值为false。
https://stackoverflow.com/questions/52893603
复制相似问题