我正在将我的 angular 应用程序从 v5 升级到 7。
我已经完成了 Angular 更新指南中提到的所有迁移步骤。但是我的现有代码面临一个问题。
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")
}
}
Run Code Online (Sandbox Code Playgroud)
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)
})
}
}
Run Code Online (Sandbox Code Playgroud)
Chr*_*odz 15
您必须使用any或 自定义响应类型,因为 typedata上不存在{}:
.subscribe((response: any) => ...)
Run Code Online (Sandbox Code Playgroud)
自定义响应接口是最好的解决方案:
export interface CustomResponse {
data: any;
}
.subscribe((response: CustomResponse) => ...)
Run Code Online (Sandbox Code Playgroud)
请注意,您还可以使用这样的类型:
this.httpClient.get<CustomResponse>(...)
.subscribe((response) => ...) // response is now CustomResponse
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5800 次 |
| 最近记录: |