TypeScript: 使用 HttpClient 的 get() 方法并订阅时出现类型错误
TypeScript: 使用 HttpClient 的 get() 方法并订阅时出现类型错误
在我的Angular应用程序中,我建立了一个服务,从MongoDB中获取一些数据作为json数组。这是我的服务代码:
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import 'rxjs/add/operator/map'; @Injectable() export class IdeaServiceService { private _getURL = '/api/1.0.0/ideas'; constructor(private _http: HttpClient) { } getIdeas() { return this._http.get(this._getURL).map((response: Response) => response.json()); } }
在另一个组件中,我尝试订阅这个服务,并将获取到的数据存储到Idea数组中(对应的我创建的类)。这是相应的代码:
import { Component, OnInit } from '@angular/core'; import { Idea } from '../idea'; import { IdeaServiceService } from '../idea-service.service'; @Component({ selector: 'app-ideas-overview', templateUrl: './ideas-overview.component.html', styleUrls: ['./ideas-overview.component.css'], providers: [IdeaServiceService] }) export class IdeasOverviewComponent implements OnInit { ideas: Array; constructor(private _ideaService: IdeaServiceService) { } ngOnInit() { this._ideaService.getIdeas().subscribe(resIdeaData => this.ideas = resIdeaData); } }
现在出现了以下类型错误:
Error:(19, 59) TS2322:Type 'Promise' is not assignable to type 'Idea[]'. Property 'includes' is missing in type 'Promise'.
非常感谢您的支持!
在使用HttpClient的get()方法并订阅时,出现了类型错误。原因是response.json()返回的是一个Promise对象,而不是一个普通的数组,所以需要使用then()方法来处理。解决方法是在订阅的回调函数中使用then()方法来获取数据,并将数据赋值给ideas变量。
具体的代码如下:
ngOnInit() { this._ideaService.getIdeas().subscribe(jsonPromise => { jsonPromise.then(resIdeaData => { this.ideas = resIdeaData; }); }); }
这样修改后,TypeScript代码不再报错。然而,在构建应用程序并在浏览器中打开时,会出现以下错误:The character encoding of the HTML document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the page must be declared in the document or in the transfer protocol. home。
为了解决这个问题,可以在index.html文件中声明字符编码,如下所示:
这样就声明了字符编码为utf-8。
在Google Chrome浏览器中,这样做可以解决问题。但是现在又出现了以下TypeError错误:TypeError: response.json is not a function。
可以参考以下链接来解决这个问题:[stackoverflow.com/questions/43008411](https://stackoverflow.com/questions/43008411)