Angular6 升级问题:类型 'Object' 上不存在属性'data'



我正在将我的角度应用程序从 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)
})
}
}

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

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

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

export interface CustomResponse {
data: any;
}
.subscribe((response: CustomResponse) => ...)

请注意,您也可以像这样使用类型:

this.httpClient.get<CustomResponse>(...)
.subscribe((response) => ...) // response is now CustomResponse

请参阅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 };
});
}

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

最新更新