【问题标题】:How to return HttpClient subscribe data to a component如何将 HttpClient 订阅数据返回给组件
【发布时间】:2018-03-30 05:34:24
【问题描述】:

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

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

组件:

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

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

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

【问题讨论】:

  • 没错,您正在获得订阅者。这就是Observable.subscribe 返回的内容,这就是您要返回的内容。可能您想要的是return this.http.get(...),并将订阅移动到组件中。或者,您可以通过另一个 observable 公开获取的数据,正如我在这里所写的:blog.jonrshar.pe/2017/Apr/09/async-angular-data.html

标签: angular typescript


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    如果你想加载数据来查看,你应该在你的服务中使用新的主题。例如:

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

    在组件中:

    export class PostsComponent implements OnInit {
        posts: any;
        constructor(private postService: PostService) { }
    
        ngOnInit() {
            this.getPosts();
        }
    
        private getPosts() {
            this.posts = this.postService.getPosts();
        }
    }
    

    在视图中:

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        【解决方案4】:

        我会在您的 .ts 中执行此操作: 私有数据$:可观察;

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

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

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

        为了得到价值。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-01-10
          • 2021-07-05
          • 2021-12-05
          • 2020-01-03
          • 2021-05-21
          • 2019-09-10
          • 2017-01-10
          • 2021-10-17
          相关资源
          最近更新 更多