Angular6升级问题:类型“对象”上不存在属性“数据”

时间:2018-10-01 09:54:25

标签: angular rxjs

我正在将我的角度应用程序从v5升级到7。

我已经完成了Angular更新指南中提到的所有迁移步骤。 但是我现有的代码面临问题。

myservice.service.ts

import {Injectable, Inject} from '@angular/core';
import { HttpClient } from '@angular/common/http';
import {Response, Headers, RequestOptions} from "@angular/http";

@Injectable()
export class MyApiService{
    constructor(private http: HttpClient, @Inject(MY_HOST) private host: string) 
    {
        this.host = this.host + "/api/common";
    }
    getNotification (appName) {
        return this.http.get(this.host + "/notifications")
    }   
}

my-component.component.ts

import {combineLatest as observableCombineLatest, Subject, Observable, Subscription} from 'rxjs';
import {MyApiService} from "../../shared/services/myservice.service";

@Component({..// template and style url...});

export class NotificationComponent implements OnInit{
    constructor(private myApiService: MyApiService)

 getNotification(): void {
     this.myApiService.getNotification('myApp').subscribe(response => {
        console.log(response.data); **// ERROR: It throws error here. Property** 'data' does not exist on type 'Object'.
    }, (error: void) => {
      console.log(error)
   })
 }

}

2 个答案:

答案 0 :(得分:2)

您必须使用any或自定义响应类型,因为data在类型{}上不存在:

.subscribe((response: any) => ...)

自定义响应界面是最佳解决方案:

export interface CustomResponse {
  data: any;
}

.subscribe((response: CustomResponse) => ...)

答案 1 :(得分:0)

请参见有关角度的HTTPClient示例:

服务代码:

getConfigResponse(): Observable<HttpResponse<Config>> {
  return this.http.get<Config>(
    this.configUrl, { observe: 'response' });
}

消费者代码:

showConfigResponse() {
  this.configService.getConfigResponse()
    // resp is of type `HttpResponse<Config>`
    .subscribe(resp => {
      // display its headers
      const keys = resp.headers.keys();
      this.headers = keys.map(key =>
        `${key}: ${resp.headers.get(key)}`);

      // access the body directly, which is typed as `Config`.
      this.config = { ... resp.body };
    });
}

通过在服务上显式声明返回类型,他们可以避免必须在订阅内部逻辑上声明返回类型,因为代码是强类型的。