2017-10-18 57 views
0

我试图使用订阅方法从服务返回数据。如何将HttpClient订阅数据返回给组件

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, …}

+0

这是正确的,你得到的用户。这就是'Observable.subscribe'返回的结果,这就是你要返回的结果。可能你想要的是'返回this.http.get(...)',并将订阅移动到组件中。或者,您可以通过另一个可观察值公开获取的数据,就像我在这里写的:https://blog.jonrshar.pe/2017/Apr/09/async-angular-data.html – jonrsharpe

回答

2

你应该认购数据,并将其分配给一个变量在组件象下面这样:

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

我会做这在你的.ts中: 私有数据$:Observable;

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

,并在您的.html模板,这样的:

<div> {{ data$ | async }} </div> 
为了得到价值

0

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

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>