如何正确订阅Angular中的Observable?

问题描述 投票:0回答:1

我的目的 是为了生成一个有效的观测值(从一个GET请求)并订阅它,这样我就可以在我的应用程序的多个不同组件中使用一次请求的数据。

我希望从服务器上得到的JSON结构如下。

{
  "one": {
    "some": "variable",
    "more": "variables"
  },
  "two": {    
    "a": "variable",
    "b": "variable"
  },
  "three": {
    "things": [
      {        
        "some": "variable",
        "more": "variables
      },
      {
        "some": "variable",
        "more": "variables"
      }
    ],
    "peoples": [
      {
        "again": "variables",
        "women": {
          "next": "variable"
        },
        "man": {
          "last": "variable"
        }
      }
    ]
  }
}

今天接近了。根据 关于请求类型化响应的Angular文档 我在一个叫api.service的服务的typcript中定义了一些数据接口。

export interface Response {
    one: One;
    two: Two;
    three: Three;
}

export interface One {
    some: string;
    more: string;
}

export interface Two {
    a: string;
    b: string;
}

export interface Three {
    things: Thing[];
    peoples: People[];
}

export interface Thing {
    some: string;
    more: string;
}

export interface People {
    again: string;
    women: Women;
    men: Men;
}

export interface Women {
    next: string;
}

export interface Men {
    last: string;
}

并写了一个函数来发送一个请求到服务中给出的url。

export classApiService {
  private url = 'https://example.com/api/1234';

  constructor(private http: HttpClient) { }

  getApiResponse() {
    // returns Observable of Type Response
    return this
      .http
      .get<Response>(this.url)
  }

现在大问题来了: 这个方法有效吗?如果是的话,我如何正确地订阅这个由 getApiResponse() 因此,我可以访问变量,例如 next 介面的 Women?

angular typescript observable httprequest angular-cli
1个回答
1
投票

是的,这就是你所要求的基本设置。所以,以你目前的设置,你可以在你的模板HTML或你的TS中订阅它。

...
public data: Observable<any[]>; // (whatever the type is instead of any)
this.data = this.getApiResponse();
...

用法,或者在你的HTML中使用

this.data.subscribe( d => console.log(d));

或者在你的HTML中使用 异步 管子

<div *ngFor="let d of data | async">{{d}}</div>

-1
投票

是的,正如 @mwilson 所述,这是基本的设置。

假设你是在 response.component.ts,这些都是你可以采取的步骤来订阅可观察的。

import {ClassApiService} from './class-api.service.ts';

data: Observable<Response[]>;

// within the constructor
constructor (private apiService: ClassApiService) {}

ngOnInit(): void {
 this.apiService.getApiResponse().subscribe(
   (results: Response[]) => this.data = results;
 );
}

然后在你的HTML模板中,比如 response.component.html -

<div *ngIf="data">
  <ul *ngFor="let d of data">
    <li>{{ d.someName }}</li>
  </ul>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.