【问题标题】:Angular perform REST petitionAngular 执行 REST 请愿
【发布时间】: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&lt;Bird[]&gt;('http://dev.contanimacion.com/birds/public/getBirds/1') 吗?

标签: angular rest get


【解决方案1】:

试试下面两种方法

一个选项是,你可以添加 async 关键字来订阅 observable

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

Observables 是惰性的,这意味着没有 subscribe ,它不会发起调用或发出 ,当你使用 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>

建议第一种方法,因为它也会在组件销毁时取消订阅 observable。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-16
    • 2018-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-23
    相关资源
    最近更新 更多