简体   繁体   English

如何正确订阅 Angular 中的 Observable

[英]How to properly subscribe to an Observable in Angular

My aim is to generate a valid observable (from a GET request) and subscribe to it, so i can use the once requested data in multiple different components of my app.我的目标是生成一个有效的 observable(来自 GET 请求)并订阅它,这样我就可以在我的应用程序的多个不同组件中使用一次请求的数据。

I expect a JSON structured like the following one from the server:我期望来自服务器的 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"
        }
      }
    ]
  }
}

Approach up today: According to the Angular Documentation on Requesting a typed response i defined some data interfaces in the typescript of a service called api.service:今天接近:根据关于请求类型化响应的 Angular 文档,我在名为 api.service 的服务的 typescript 中定义了一些数据接口:

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;
}

And wrote a function that sends a request to a url given in the service:并编写了一个 function 向服务中给出的 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)
  }

And now the big questions rise: Is this approch valid?现在出现了一个大问题:这种方法有效吗? And if yes, how do i properly subscribe the Observable returned by getApiResponse() so i can eg access the variable next of the interface Women ?如果是,我如何正确订阅getApiResponse()返回的 Observable,以便我可以访问接口Womennext变量?

Yes, this is the basic setup for what you're asking.是的,这是您所要求的基本设置。 So, with you're current setup, you could can subscribe to it within your template HTML or your TS:因此,使用您当前的设置,您可以在您的模板 HTML 或您的 TS 中订阅它:

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

Usage:用法:

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

or in your HTML using the async pipe或在您的 HTML 中使用异步pipe

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

Yeap, as @mwilson mentioned that is the basic setup.是的,正如@mwilson 提到的,这是基本设置。

Assuming you are on response.component.ts , these are the steps you could take to subscribe to the observable:假设您在response.component.ts上,您可以采取以下步骤订阅 observable:

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;
 );
}

Then within your HTML template, say response.component.html -然后在您的 HTML 模板中,说response.component.html -

<div *ngIf="data">
  <ul *ngFor="let d of data">
    <li>{{ d.someName }}</li>
  </ul>
</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM