[英]Angular BehaviorSubject; the “next” method doesn't work
I have a code that I wrote back in Angular 4 and it worked perfectly, now part of it is broken in Angular 6 and I appreciate some help. 我有一个我在Angular 4中写的代码,它可以完美地工作,现在它的一部分在Angular 6中已损坏,我希望能得到一些帮助。
I have an AuthService
class: 我有一个
AuthService
类:
export class AuthService {
private loggedIn = new BehaviorSubject<boolean>(false);
isUserLoggedIn(): Observable<boolean> {
return this.loggedIn.asObservable();
}
isUserLoggedIn(): Observable<boolean> {
return this.loggedIn.asObservable();
}
login(username: string, password: string) {
let body =
{
username: username,
password: password
};
return this._http.post(Settings.apiEndpoint + "users/authenticate", body)
.map(res => {
localStorage.setItem('token', res["token"]);
localStorage.setItem('username', res["username"]);
this.isLoggedIn = true;
this.loggedIn.next(true);
return res;
})
.catch(error => {
this.clearAuthData();
return Observable.throw(error)
});
}
logout() {
localStorage.clear();
this.isLoggedIn = false;
this.loggedIn.next(this.isLoggedIn);
}
}
and in my AppComponent
, I subscribe to this subject like this in the ngOnInit: 在我的
AppComponent
,我在AppComponent
订阅了这个主题:
this._auth.isUserLoggedIn()
.subscribe(
d => {
console.log("d here", d);
if (d)
{
this.isLoggedIn = true;
this.username = this._auth.getUsername();
}
else {
this.isLoggedIn = false;
}
},
d => {
console.log("error.");
},
() => {
console.log("bull.");
}
);
The issue is when I logout, the AppComponent does react to the observable, but when I login it doesn't. 问题是当我注销时,AppComponent确实对可观察到的对象做出了反应,但是当我登录时却没有。 The code is untouched as far as I can tell from what it was in Angular 4, so I cannot figure out why it is not firing.
据我从Angular 4的内容来看,该代码是未经修改的,因此我无法弄清楚为什么它不触发。
Your code doesn't work beause of rxjs 6 breaking change, version 5.5 introduced pipeable operators 您的代码无法正常工作,因为rxjs 6发生了重大变化,引入了5.5版可管道运算符
Before: 之前:
source.map(x => x * 2).catch(() => of('ups'))
Now: 现在:
source.pipe(map(x => x * 2), catchError(() => of('ups')))
also they moved catch() to catchError(), do() to tap(), switch() to switchAll() and finally() to finalize() 他们也将catch()移到catchError(),do()移到tap(),switch()移到switchAll(),finally()移到finalize()
[Edit] don't forget to import your rxjs operators like that: import { map } from 'rxjs/operators'; [编辑]不要忘了像这样导入您的rxjs运算符:从'rxjs / operators'导入{map};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.