angular - 角度行为主题;“下一个”方法不起作用
问题描述
我有一个我在 Angular 4 中写回的代码,它运行良好,现在它的一部分在 Angular 6 中被破坏了,我感谢一些帮助。
我有一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);
}
}
在我AppComponent
的 ngOnInit 中,我像这样订阅这个主题:
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.");
}
);
问题是当我注销时,AppComponent 确实对 observable 做出反应,但是当我登录时它没有。据我所知,代码在 Angular 4 中的内容没有受到影响,所以我无法弄清楚为什么它没有触发。
解决方案
由于 rxjs 6 重大更改,您的代码不起作用,版本 5.5 引入了可管道操作符
前:
source.map(x => x * 2).catch(() => of('ups'))
现在:
source.pipe(map(x => x * 2), catchError(() => of('ups')))
他们还将 catch() 移至 catchError(),将 do() 移至 tap(),将 switch() 移至 switchAll(),将 finally() 移至 finalize()
[编辑] 不要忘记像这样导入你的 rxjs 操作符: import { map } from 'rxjs/operators';
推荐阅读
- java - 错误:不兼容的类型:意外的返回值 Char 与 String 比较
- php - 重复数字数组,php
- c# - 如何为此代码块编写单元测试
- java - Citrus 框架“[520] 没有匹配的常量” - 自定义 HTTP 状态代码
- google-cloud-datastore - Google 数据流 - 使用数据存储选项连接到数据存储会出现错误
- c# - 如何获取 xpath 中的最后一个表?
- aws-lambda - 尖峰 AWS Lambda 函数
- fortran - 查询无格式文件fortran
- node.js - 如何从 REST API 输出信息
- python - 当我将两位艺术家叠加在同一位置时,最低的一位仍然以某种方式显示