gpt4 book ai didi

angular - 如何在 Angular 中订阅 Observable

转载 作者:搜寻专家 更新时间:2023-10-30 21:25:26 25 4
gpt4 key购买 nike

我正在尝试订阅一个 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 中显示它

最佳答案

你不需要订阅,async pipe 会为你订阅并获取值🧙‍♂️

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);

}

The async pipe takes care of subscribing and unwrapping the data as well as unsubscribing when the component is destroyed, so you don't need subPlayer

模板

<ng-container *ngIf="(player$ | async) as player">
<div *ngIf="player.characterUid">
{{player.characterName}}
</div>
</ng-container>

Async Pipe 🔥

关于angular - 如何在 Angular 中订阅 Observable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57396499/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com