我只是在看这个例子https://github.com/arjunyel/angular-apollo-example/blob/master/frontend/src/app/app.component.ts#L28
它具有以下代码:
this.tweets = this.tweetsGQL
.watch()
.valueChanges.pipe(map(tweets => tweets.data));
Run Code Online (Sandbox Code Playgroud)
只是想知道如何this.tweets获得分配的值?它是事做.pipe(map()),你可以给一些细节?
在 Angular 中,要在 *ngFor 中显示数据,我们可以采取两种方法:
使用 async 显示可观察对象。通常我们使用可观察变量以 $ 开头的约定
<div *ngFor="let tweet of ($tweets | async)?.tweets">
....
</div>
//In this case we use
this.$tweets=this.tweetsGQL
.watch()
.valueChanges.pipe(map(res=> res.data));
Run Code Online (Sandbox Code Playgroud)
显示数组
<div *ngFor="let tweet of tweets.tweets">
....
</div>
//In this case we must subscribe -and not equal the observable to anything
this.tweetsGQL
.watch()
.valueChanges.pipe(map(res=> res.data))
.subscribe(res=>this.tweets=res);
Run Code Online (Sandbox Code Playgroud)
关于“地图(tweets=>twees.data)”。observable 可以返回任何东西。在这种情况下返回一个像这样的对象
{data:tweets:[....],otherProperty:value}
Run Code Online (Sandbox Code Playgroud)
我们可以映射(转换)响应,以便可观察对象仅返回“属性”数据。不是整个物体
map(res=>res.data)
//the for must be over tweets.tweets *ngFor="let tweet of tweets.tweets"
Run Code Online (Sandbox Code Playgroud)
甚至我们可以映射响应,以便可观察的返回 data.tweets
map(res=>res.data.tweets)
//the for must be over tweets *ngFor="let tweet of tweets"
Run Code Online (Sandbox Code Playgroud)
注意:我使用变量“res”更改响应以避免混淆
| 归档时间: |
|
| 查看次数: |
469 次 |
| 最近记录: |