组件.html:
<div *ngIf="!isWaiting">
<h2>LOGIN</h2>
<p>{{ message | async }}</p>
<div *ngIf="!(isLoggedIn | async)">
<button (click)="login()">{{'StrLogin' | translate}}</button>
</div>
<div *ngIf="(isLoggedIn | async)">
<button (click)="logout()">{{'StrLogout' | translate}}</button>
</div>
</div>
<div *ngIf="isWaiting">
<p>initializing</p>
</div>
组件.ts
message: Observable<string>;
login(name : string, password : string): void {
this.message = this.tokenService.login(name, password)
.pipe(
map((token) => {
console.debug('login succeeded: %s', JSON.stringify(token));
return 'success';
}),
catchError(err => {
console.debug('login failed: %s', JSON.stringify(err));
return 'failed';
})
);
}
当这失败时,仅显示字母“d”(“失败”)。如果我将其更改为:
catchError(err => {
console.debug('login failed: %s', JSON.stringify(err));
return '123';
})
它显示 3。
最佳答案
catchError()
运算符期望回调函数返回一个可观察的。我不确定它为什么会呈现 3
但很可能该字符串已转换为一个可观察的数组,该数组按顺序发出每个字符。
https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/catchError.ts#L90
catchError(err => {
console.debug('login failed: %s', JSON.stringify(err));
return of('failed');
})
https://www.learnrxjs.io/operators/error_handling/catch.html
使用
async
时模板中的管道。请记住,如果 DOM 被 *ngIf
突变,它将调用 subscribe再高。因此,如果 observable 来自 HTTP 请求,则添加 shareReplay(1)
运算符并且仅在模板中使用相同的对象引用。
关于angular - 为什么只显示 Angular 异步管道绑定(bind)中字符串的最后一个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56410427/