【问题标题】:Angular: Object iterable with ngFor but not in Typescript?Angular:对象可与 ngFor 迭代,但不能在 Typescript 中迭代?
【发布时间】:2018-08-31 05:01:24
【问题描述】:

我有以下几点:

public posts: QueryRef<PostsInterface>;

this.posts = this._postService.get(); //in ngOnInit

并在相应的HTML中:

<mat-card *ngFor="let post of posts | async">

然后可以使用 {{post.name}} 等在 html 中显示每个帖子的字段。

我的问题是,如何通过 typescript 中的帖子 QueryRef 实现相同的迭代?当我尝试以下操作时:

for (let post of this.posts) {
      console.log("Post name is: " + post.name);
    }

我收到错误"Type 'QueryRef&lt;PostsInterface, Record&lt;string, any&gt;&gt;' is not an array type or a string type." 如果 ngFor 能够遍历 QueryRef,那么在 typescript 本身中一定有一些方法可以做到吗?

最终我想用分页器在表格中显示数据。使用 mat-table 无法实现这一点。有没有在 mat-table 中显示使用 apollographql 抓取的数据的示例?

更新: 我尝试像这样订阅 ngOnInit:

this.posts.valueChanges.subscribe((post1: ApolloQueryResult<PostsInterface>) => {
        console.log("name is: "+ post1.name)
    });

但这给出了错误:“ApolloQueryResult”类型上不存在属性“名称”。同样,如上所述,在使用 *ngFor 和异步管道进行迭代时,可以毫无问题地访问此属性。

第二次更新: 我了解到 QueryRef 实际上根本不是 Observable 或可迭代的,这导致我发现帖子被错误地键入为 QueryRef,而它应该是 Observable。这发生在我迁移到 Apollo 2.0 时;我只是做得不对。

【问题讨论】:

    标签: angular typescript rxjs ngfor apollo-client


    【解决方案1】:

    async 管道等待查询结果。你也必须在你的 TypeScript 代码中这样做。这可能由subscribingthis.posts.valueChanges 完成,这应该是observable

    【讨论】:

    • 我试过了,请看上面的更新。使用 subscribe() 时无法访问数据,即使 ngFor |异步访问它就好了
    • 你可以看看ApolloQueryResult的界面,如果你的代码中的所有内容都输入正确,你需要访问它的data属性,在你的情况下应该包含一个PostsInterface
    【解决方案2】:

    除了@H.B.说,你的错误描述:

    “我收到错误“键入'QueryRef>' 不是数组类型或字符串类型。”

    让我相信 this.posts 是一个对象,在这种情况下你不能使用 for'of 语法。对于必须使用 for'in 的对象。

    for (let key in this.posts) {
          console.log("Post name is: " + this.posts[key].name);
        }
    

    【讨论】:

    • 这是一个错误的推论。仅仅因为对象不能被迭代,并不意味着对象本身应该被迭代。您不能假设密钥将包含您需要的数据。
    • 试过了,它消除了编译错误,但它给出了垃圾数据。
    • 您能否举例说明this.post 对象的外观?在不知道有问题的对象是什么的情况下,很难理解为什么它不起作用。
    猜你喜欢
    • 2020-11-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-11
    • 1970-01-01
    • 2023-04-06
    • 2019-06-03
    • 2017-02-09
    • 2018-04-13
    相关资源
    最近更新 更多