[英]Angular6 upgrade issue: Property 'data' does not exist on type 'Object'
I am upgrading my angular app from v5 to 7.我正在将我的 angular 应用程序从 v5 升级到 7。
I have done all of the migration steps mentioned in Angular update guide.我已经完成了 Angular 更新指南中提到的所有迁移步骤。 But I am facing an issue with my existing code.
但是我的现有代码面临一个问题。
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")
}
}
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)
})
}
}
You must use any
or a custom response type since data
doesn't exist on type {}
:您必须使用
any
或自定义响应类型,因为类型{}
上不存在data
:
.subscribe((response: any) => ...)
A custom response interface is the best solution:自定义响应接口是最好的解决方案:
export interface CustomResponse {
data: any;
}
.subscribe((response: CustomResponse) => ...)
Note that you can also use the type like this:请注意,您还可以使用这样的类型:
this.httpClient.get<CustomResponse>(...)
.subscribe((response) => ...) // response is now CustomResponse
See this example from the angular documentation for HTTPClient:从 HTTPClient 的角度文档中查看此示例:
Service code:服务代码:
getConfigResponse(): Observable<HttpResponse<Config>> {
return this.http.get<Config>(
this.configUrl, { observe: 'response' });
}
Consumer Code:消费者代码:
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 };
});
}
By declaring the return type explicitly on the service they can avoid having to declare it on the subscription inner logic because the code is strongly typed.通过在服务上显式声明返回类型,他们可以避免在订阅内部逻辑上声明它,因为代码是强类型的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.