【问题标题】:TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Object'TS7053:元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型“对象”
【发布时间】:2021-08-08 22:36:49
【问题描述】:

我尝试直接使用 templateDrivenForm 发布数据并从 fireBase 获取数据,但显示以下类型错误。

我的部分代码

//directly posts datas using submitButton from templateDrivenForm
 onCreatePosts(postDatas:{title:string, content:string}){
this.http.post('https://ng-complete-guide-b3d7f-default-rtdb.firebaseio.com/posts.json',
 postDatas)
.subscribe(
 responseData => {
  console.log(responseData);
 });
 }

 //get datas from database
   private fetchPost(){
     return this.http.get('https://ng-complete-guide-b3d7f-default-rtdb.firebaseio.com/posts.json')
   .pipe(map(responseData =>  {
     const dataArray = [];
    for(let key in responseData){
    if(responseData.hasOwnProperty(key)){
    dataArray.push({...responseData[key], id:key});
    }
  }
  return dataArray;
 }))
  .subscribe( responseData => {
  console.log(responseData)
 })
}

我的错误是

     Error: src/app/app.component.ts:40:28 - error TS7053: Element implicitly has an 'any' type 
      because 
     expression of type 'string' can't be used to index type 'Object'.
      No index signature with a parameter of type 'string' was found on type 'Object'.

     40         dataArray.push({...responseData[key], id:key});

【问题讨论】:

    标签: java html css angular typescript


    【解决方案1】:

    解决办法

          private fetchPost(){
          return this.http.get('https://ng-complete-guide-b3d7f-default- 
          rtdb.firebaseio.com/posts.json')
        .pipe(map((responseData:{[data:number]:any}) =>  {
         const dataArray = [];
         for(let key in responseData){
      if(responseData.hasOwnProperty(key)){
        dataArray.push({...responseData[key], id:key});
      }
      }
        return dataArray;
      }))
     .subscribe( responseData => {
      console.log(responseData)
     })
     }
    
     .pipe(map((responseData:{[data:number]:any}) //object type
    

    【讨论】:

    • 我认为你的 id 是一个字符串,你应该尽可能避免使用any。类型应该是{ [key:string]: { content: string, title: string } }
    • 你能在你的函数中合并帖子对象(至少部分)并显示哪些字段来了?但是在你的位置,而不是使用 REST API(与库相比,它非常有限),我建议使用一个特殊的库来与 firebase 一起使用 angular npmjs.com/package/@angular/fire
    猜你喜欢
    • 1970-01-01
    • 2021-10-19
    • 2021-08-28
    • 2021-03-17
    • 2021-04-20
    • 1970-01-01
    • 1970-01-01
    • 2020-08-24
    • 2020-11-13
    相关资源
    最近更新 更多