简体   繁体   中英

How to return HttpClient subscribe data to a component

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:

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

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

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

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

and in your .html template, this:

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

in order to get the value.

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>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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