【问题标题】:returning Array Observable from watchQuery function GraphQL, but giving *ngFor error从 watchQuery 函数 GraphQL 返回 Array Observable,但给出 *ngFor 错误
【发布时间】:2017-10-20 09:05:50
【问题描述】:

我收到 [ 错误:NgFor 仅支持绑定到可迭代对象,例如数组。 ]

我做错了什么?

View Code : 
<div *ngFor="let item of data| async" class="wide-box">

组件代码:

public data : ApolloQueryObservable

调用watchQuery函数,在map函数中进行一些后期处理,返回Array的Observable,

public feed(){
    var a = gpl`
    query user($user: UserInput){
    user(user:$user){
        first_name
        lync{
            artist
            title
            albumArtUrl
            listenon
            date
            author{
                username
                email
            }
        }
        following{
            lync {
                artist
                title
                albumArtUrl
                listenon
                date
                author{
                  username
                  email
                }
            }
        }
    }
}
`;
this.data = this.apollo.watchQuery({
    query: a,
    variables: {
            user: {
                email: window.localStorage.getItem('email')
            }
        }
    }).map((x:any)=>x.data.user[0]).map(x=>{
        this.feedItem = []  
        if(x.lync.length){
            x.lync.map(l=>{
                if(l!=undefined){
                    this.feedItem.push(l)
                }
            })
        }
        if(x.following){
            x.following.map(y=>{
                if(y.lync.length != 0){
                    y.lync.map(l=>{
                        if(l!=undefined){
                            this.feedItem.push(l)
                        }
                    })
                }
            })
        }

        console.log(this.feedItem, "feedItem")
        return ApolloQueryObservable.of(this.feedItem)
    })

从服务器重新获取数据

public refresh(){
   this.data.refetch()
  }

【问题讨论】:

  • 我只在documentation 上花了几分钟,但你的整个方法似乎与它完全不一致。例如,我只是直接链接到使用异步管道的部分。正如我所料,文档:1. 明确建议在 ngOnInit() 挂钩中设置 watchQuery,2. 直接从函数中干净地返回 observable。看起来你.map() 处理真的把结构弄乱了。值得注意的是x.data.user[0] 在这里似乎真的错了。

标签: angular rxjs graphql apollo apollo-client


【解决方案1】:

我不明白发生了什么,但我看到 watchQuery 中的最后一个 map 运算符没有返回任何对象。

因此 this.data 很可能被 null 填充

【讨论】:

  • 请注意,这些 .map() 语句中有 .push() 操作。为了清楚起见,它们可能应该写成.forEach()。或者使用扩展运算符可能会更好。预期回报是this.feedItem 的值。所以这不是因为.map() 语句缺少return
猜你喜欢
  • 2021-07-17
  • 1970-01-01
  • 1970-01-01
  • 2020-04-24
  • 1970-01-01
  • 1970-01-01
  • 2017-04-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多