【发布时间】:2019-06-07 20:47:07
【问题描述】:
我正在尝试使用 Angular 执行 GET,但它不起作用。
我有一个在构造函数上注入自定义服务的组件,该服务执行其余请求并将结果存储在数组中。
以下是bird.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
interface Bird {
id: number;
bird_name: string;
bird_image: string;
bird_sightings: string;
mine: number;
}
@Injectable()
export class BirdService {
constructor(private http: HttpClient) {
this.getBirds().subscribe(data => this.birds = data);
}
birds: Bird[];
getBirds() {
return this.http.get('http://dev.contanimacion.com/birds/public/getBirds/1');
}
}
以下是bird.page.ts
import { Component, OnInit } from '@angular/core';
import { BirdService } from '../bird.service';
@Component({
selector: 'app-birds',
templateUrl: './birds.page.html',
styleUrls: ['./birds.page.scss'],
})
export class BirdsPage implements OnInit {
constructor(public birdService: BirdService) { }
ngOnInit() {
}
}
最后是bird.page.html
<ion-content>
<div *ngFor="let bird of birdService.birds"></div>
</ion-content>
我收到以下错误:
[ng] ERROR in src/app/bird.service.ts(16,40): error TS2322: Type 'Object' is not assignable to type 'Bird[]'.
[ng] The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?
[ng] src/app/bird.service.ts(16,40): error TS2322: Type 'Object' is not assignable to type 'Bird[]'.
[ng] The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?
[ng] Property 'length' is missing in type 'Object'.
【问题讨论】:
-
我发现了一些问题。 1. 你永远不会订阅 HTTP REST 返回的 observable。因此,该请求永远不会被触发。如果您要查看开发工具中的网络选项卡,您是否看到请求发出痛风?您可以订阅 BirdPage.ts 组件文件中的服务。或者您可以在模板中使用“异步”管道。这样做会自动为您订阅服务。将您的课程更改为类似 this.birds = this.birdservice.getBirds() 的内容。然后在您的模板中执行 *ngFor="let bird of bird | async" 应该可以满足您的需求。
-
@Edward First 订阅在服务构造函数中,如果您添加
| async并在其周围使用*ngIf,它将调用太多次服务。这更像是一个转译错误。你试过this.http.get<Bird[]>('http://dev.contanimacion.com/birds/public/getBirds/1')吗?