0
votes

I have the following:

public posts: QueryRef<PostsInterface>;

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

And in the corresponding HTML:

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

And then am able to display each post's fields in html using {{post.name}}, etc.

My question is, how can I achieve the same iteration through the posts QueryRef inside typescript? When I try the following:

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

I get the error "Type 'QueryRef<PostsInterface, Record<string, any>>' is not an array type or a string type." If ngFor is able to iterate through the QueryRef, there must be some way to do it in the typescript itself?

Ultimately I want to display the data in a table with a paginator. Having trouble achieving this with mat-table. Are there any examples of displaying data grabbed with apollographql in a mat-table?

Update: I tried subscribing in ngOnInit like so:

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

But this gives the error: Property 'name' does not exist on type 'ApolloQueryResult'. Again, this property can be accessed with no problem when iterating with the *ngFor and async pipe as described above.

Second update: I learned that QueryRef is not actually an Observable or iterable at all, which led me to discover that posts is being incorrectly typed as QueryRef, when it should be an Observable. This happened when I was migrating to Apollo 2.0; I just didn't do it right.

2

2 Answers

0
votes

The async pipe awaits the results of the query. You would have to do that in your TypeScript code as well. This can probably be done by subscribing to this.posts.valueChanges which should be an observable.

0
votes

In addition to what @H.B. said, your error description:

"I get the error "Type 'QueryRef>' is not an array type or a string type."

Leads me to believe that this.posts is an object in which case you cannot use the for'of syntax. For objects you have to use for'in.

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