Angular执行REST请愿

时间:2019-06-07 20:47:07

标签: angular rest get

我正在尝试使用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 个答案:

答案 0 :(得分:0)

尝试以下两种方法

一个选择是,您可以添加async关键字以订阅可观察的

<div *ngFor="let bird of birdService.getBirds()|async"></div>

可观察对象是惰性的,这意味着如果没有订阅,它将不会发起呼叫或发出信号,当您使用async关键字angular时会自动为您订阅。

您还可以像下面这样手动订阅。

constructor(private birdService: BirdService) { }
  birds:Bird[];
  ngOnInit() {
    this.birdService.getBirds().subscribe((res)=>{
   this.birds=res;
     });
  }

<div *ngFor="let bird of birdService.birds"></div>

建议采用第一种方法,因为当组件销毁时,它也将取消对可观察对象的约束。

也不建议订阅服务构造函数,始终将视图模型放在组件上。