Angular 2中带有两个http.get调用的可观察类型 [英] Observable type with two http.get calls in Angular 2

查看:50
本文介绍了Angular 2中带有两个http.get调用的可观察类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的ng2服务中,我有一个具有2个http.get调用的方法.该函数看起来像这样:

In my ng2 service, i have a method that has 2 http.get calls. The function looks something like this:

getInfo(userId: number): any {

    this.http
       .get(apiUrl, options)
       .map(response => response.json())
       .subscribe(example => {
           this.example.FirstName = example.FirstName;
           this.example.LastName = example.LastName;

           this.http
               .get(`/api/${userId}`)
               .map(response => response.json())
               .subscribe(example => {
                   this.example.Street = example.Street;
                   this.example.City = example.City;

                   return this.example;
               });
       });
 }

唯一的问题是,在我的组件中,我无法订阅此函数,因为它的类型不是 Observable< Example> .

The only problem is that, in my component, i can't subscribe to this function, because it's not of type Observable<Example>.

如果我用 Observable< Example> 替换函数的any类型,则会得到:

If I replace the type any for the function with Observable<Example> I get :

声明类型既不是"void"也不是"any"的函数必须返回值

但是我确实在响应后返回了一个值.

But I do return a value, after the response.

如何在没有两个独立功能的情况下执行此操作?

How can I do this without having two separate functions?

是的,我确实检查了以下答案: https://stackoverflow.com/a/36712707/3264998

Yes, i did checked this answer: https://stackoverflow.com/a/36712707/3264998

推荐答案

尝试将其作为方法主体编写,这是解决此问题的一种方法.

Try writing this as your method body, this is one way there are other ways to solve this.

return this.http
   .get(apiUrl, options)
   .map(response => response.json())
   .flatMap(example => {
       this.example.FirstName = example.FirstName;
       this.example.LastName = example.LastName;

       return this.http
           .get(`/api/${userId}`)
           .map(response =>  {
               let example =response.json();
               this.example.Street = example.Street;
               this.example.City = example.City;

               return this.example;
           });
   });

这篇关于Angular 2中带有两个http.get调用的可观察类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆