[英]How to subscribe to an Observable in Angular
我试图订阅一个Observable,所以我可以用Angular在HTML中显示它,但是console.log(player)
可以正常工作,但是我得到了
Type 'Player' is missing the following properties from type 'Observable<Player>': _isScalar, source, operator, lift, and 6 more.ts(2740)
我尝试使用.pipe()
,
HTML:
<div *ngIf="(player$ | async) as player">
<div *ngIf="player.characterUid">
{{player.characterName}}
</div>
</div>
零件:
player$: Observable<Player>;
subPlayer: Subscription;
selectPlayer(matEvent: MatAutocompleteSelectedEvent): void {
this.inputFriends = matEvent.option.value;
this.selectedPlayer = matEvent.option.value;
this.inputP = false;
this.subPlayer = this.playerProvider.get$(matEvent.option.value.userUid).subscribe(
(player: Player) => {
this.player$ = player; // Type 'Player' is missing the following properties from type 'Observable<Player>': _isScalar, source, operator, lift, and 6 more.ts(2740)
}
);
}
提供者:
get$(uid: string): Observable<Player> {
return this._getDoc(uid)
.valueChanges()
.pipe(
map((sPlayer: ServerPlayer) => sPlayer ? new Player(sPlayer) : null)
);
}
private _getDoc(uid: string): AngularFirestoreDocument {
return this.afs.doc(`players/${uid}`);
}
我只是想分配player$
以便可以在HTML中显示它
在您的代码player$
中不是可观察的,它已经是可观察的结果。
player: Player; // <-- here
subPlayer: Subscription;
selectPlayer(matEvent: MatAutocompleteSelectedEvent): void {
this.inputFriends = matEvent.option.value;
this.selectedPlayer = matEvent.option.value;
this.inputP = false;
this.subPlayer = this.playerProvider.get$(matEvent.option.value.userUid).subscribe(
(player: Player) => {
this.player = player; // <-- here
}
);
}
<div *ngIf="player"> <!-- here -->
<div *ngIf="player.characterUid">
{{player.characterName}}
</div>
</div>
您不需要订阅,异步管道将订阅并为您获取价值🧙♂️
player$: Observable<Player>;
selectPlayer(matEvent: MatAutocompleteSelectedEvent): void {
this.inputFriends = matEvent.option.value;
this.selectedPlayer = matEvent.option.value;
this.inputP = false;
this.player$= this.playerProvider.get$(matEvent.option.value.userUid);
}
异步管道负责订阅和解包数据以及在组件销毁时取消订阅,因此您不需要subPlayer
模板
<ng-container *ngIf="(player$ | async) as player">
<div *ngIf="player.characterUid">
{{player.characterName}}
</div>
</ng-container>
我只是想分配玩家$,以便可以在HTML中显示它
this.player$ = this.playerProvider.get$(matEvent.option.value.userUid);
此方法返回一个可观察的值,因此,如果要分配player$
,则可以这样做。 在您的html模板中,您正在使用| async
| async
处理自动订阅/取消订阅。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.