typescript 如何将 HttpClient 订阅数据返回给组件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46808560/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:58:53  来源:igfitidea点击:

How to return HttpClient subscribe data to a component

angulartypescript

提问by Rahul Dagli

I'm trying to return data from a service using subscribe method.

我正在尝试使用订阅方法从服务返回数据。

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class DevRequestService {
    constructor(private http: HttpClient){}
    getListOfAgencies() {
        return this.http.get('https://example.com/api/agency').subscribe(data => {
            return data;
          });
    }
}

Component:

零件:

ngOnInit(): void {
  console.log(this.devRequestService.getListOfAgencies());
}

Below is the output that I'm getting in console.log instead of returning the object with the values:

下面是我在 console.log 中得到的输出,而不是返回带有值的对象:

Subscriber {closed: false, _parent: null, _parents: null, _subscriptions: Array(1), syncErrorValue: null,?…}

Subscriber {closed: false, _parent: null, _parents: null, _subscriptions: Array(1), syncErrorValue: null,?…}

回答by Preethi

You should subscribe for the data and assign it to a variable in component like below:

您应该订阅数据并将其分配给组件中的变量,如下所示:

ngOnInit(): void {
   this.devRequestService.getListOfAgencies().subscribe((data) => {
      this.agencies = data;
   })
};

回答by gsamaras

I would do this in your .ts: private data$: Observable;

我会在你的 .ts: private data$: Observable; 中这样做。

ngOnInit(): void {
    this.data$ = this.devRequestService.getListOfAgencies();
}

and in your .html template, this:

在你的 .html 模板中,这个:

<div> {{ data$ | async }} </div>

in order to get the value.

以获得价值。

回答by Vadim Vadim

If you want to load data to view, you should use new Subject in your service. For example:

如果要加载数据以进行查看,则应在​​服务中使用新的主题。例如:

export class PostService {
    subject = new Subject();
    constructor(private httpClient: HttpClient) {}

    const httpRequest = new HttpRequest(
        'GET',
        '/your-url',
        body,
        {
            headers: new HttpHeaders().set('Content-Type', 'body'),
        }
    );
    this.httpClient.request(httpRequest).subscribe((res) => {
        if (res.type) {
            this.subject.next(res.body);
        }
    });

    return this.subject;
}

In component:

在组件中:

export class PostsComponent implements OnInit {
    posts: any;
    constructor(private postService: PostService) { }

    ngOnInit() {
        this.getPosts();
    }

    private getPosts() {
        this.posts = this.postService.getPosts();
    }
}

In view:

鉴于:

<app-post-item
    class="col-md-4"
    *ngFor="let post of posts | async"
    [post]="post">
</app-post-item>

回答by Aaron

I also had this problem where I was not getting a response, but rather a subscriber instance. It turned out the server code was not returning a JSON parsable response. Seemed like a silent error, not sure why. But when I fixed the server code to return an object, I got the response.

我也遇到了这个问题,我没有得到响应,而是一个订阅者实例。结果发现服务器代码没有返回一个 JSON 可解析的响应。似乎是一个无声的错误,不知道为什么。但是当我修复服务器代码以返回一个对象时,我得到了响应。