角度处理一个json对象编译但抛出错误

时间:2018-06-21 17:32:39

标签: angular typescript http

我在angular6项目中具有以下组件。

export class BoxdataComponent implements OnInit {
  numberOnSite: Object;
  number: number;
  numberClicks: Object;
  constructor(private _pullAnalyticsService: PullanaliticsService) {}

  ngOnInit() {
    timer(0, 5000).pipe(
      switchMap( _ => this._pullAnalyticsService.httpGetAsync()
    )).pipe(
      map(ret => {
        console.log(ret.ListOfData[0]); // ListOfData[0]);
        console.log(ret.ListOfData[1]);
        this.numberOnSite = ret.ListOfData[0];
        this.numberClicks = ret.ListOfData[1];
      })
    ).subscribe();
  }

}

其中httpGetAsync()在服务中定义为。

  httpGetAsync() {
      return this.httpClient.get(this.theUrl);
  }

现在一切正常,我在控制台中看到正确的数据,并且numberOnSite和numberClicks是正确的值。但是我得到了错误:

ERROR in src/app/boxdata/boxdata.component.ts(22,25): error TS2339: Property 'ListOfData' does not exist on type 'Object'.
src/app/boxdata/boxdata.component.ts(23,25): error TS2339: Property 'ListOfData' does not exist on type 'Object'.
src/app/boxdata/boxdata.component.ts(24,33): error TS2339: Property 'ListOfData' does not exist on type 'Object'.
src/app/boxdata/boxdata.component.ts(25,33): error TS2339: Property 'ListOfData' does not exist on type 'Object'.

注意:ret是一个json对象。

定义为:

{"ListOfData": [  4467 , 4065 ]}

成功刷新项目后,将引发这些错误。另外,如果我使用ctrl-C停止项目并运行ng serve,则该项目将不再“编译”。但是,如果我删除有问题的行,请运行ng serve,然后再次将其改回即可。为什么项目要这样做?我在与代码,如果这有什么关系。谢谢。

2 个答案:

答案 0 :(得分:1)

将管道更改为

map((ret:any) => {

这是由类型检查引起的编译错误,因为ret被视为类型为Object的对象,它没有ListOfData属性。

通过键入ret:any,我们将删除类型检查,并说它可能具有任何属性

答案 1 :(得分:0)

请删除“ Object”声明的变量,让我们这样声明

numberOnSite:any; //如果您的变量数组这样使用any [] = []: numberClicks:any;