2017-04-20 81 views
1

我有这个function1(),它调用function2(),它返回一个Observable。从另一个可观测值中获得值

功能1

function1(url: string):Observable<boolean> { 

     return this.function2().map(res=>{ 
       if (this.data== true) 
       { 
        return true; 
      } 
      else{ 
       this.router.navigate(['/error-user']); 
       return false; 
      } 
      }); 

而且function2()调用另一个功能function3()

函数2

function2(){ 
    debugger; 
    return this.service.getSettings() 
     .do(

        response => { 

         //some data 

         this.function3(); 
         //this.data from function3() should be accesible here              
        }); 

    } 

function3()预订了服务电话。

功能3

function3(){ 

      this.service.getUserInfo() 
          .subscribe(
           response => {       
            //some data 
            this.data=true; 
           }) 

      } 

现在,我要的是在function3()this.data是在function2()入店因为我使用map操作使得在function1()使用它。

我迄今试图像下面的东西:

function2(){ 
    debugger; 
    return this.service.getSettings() 
     .do(

        response => { 

         //some data 

         this.function3().map(
        ()=> console.log(this.data)).subscribe(()=>{return this.data}); 
         //this.data from function3() should be accesible here              
        }); 

    } 

function3(){ 

      return this.service.getUserInfo() 
          .do(
           response => {       
            //some data 
            this.data=true; 
           }) 

      } 

但随着像上面我不能够在函数2的范围,以获得this.data从功能3()()的值。进一步this.data也应该传递给function1()。

回答

0

使用Observable也为function3()

function3():Observable<any> { 
    // do stuff and get data 
    return data; 
    } 

然后订阅它,你需要调用它和访问它的数据:

this.function3().subscribe((data) => { 
     let myData = data; // for using it inside this block 
     console.log(myData); 
    }); 

更新1:

function2(){ 
    let myData = {}; // if data an obj 
    debugger; 
    return this.service.getSettings() 
     .do(

        response => { 

         //some data 

         this.myData = this.function3().subscribe((data) => { 
         return data; 
         }); 
         // the data from function3() is now available here              
        }); 

    } 

更新2:

另一个更好理解的例子。这是我如何使用它:

功能:

getLoginInfo(): Observable<any> { 
     return this.jsonApiService.fetch('/user/login-info.json') 
      .do((user) => { 
       this.userInfo = user; 
       this.user.next(user); 
      }); 
    } 

这里是我把它拿到数据:

private user: any; 

    constructor(private userService: UserService) { 
    } 

    ngOnInit() { 
     this.userService.getLoginInfo().subscribe(user => { 
      this.user = user; 
     }); 
    } 
+0

功能3时返回一个可观察到的只有你明白我的在这个问题上从我身边试过。 –

+0

@AakashThakur为什么不在'function2()'里面调用'getUserInfo()'? – SrAxi

+0

@AakashThakur无论如何,要访问'function3()',你可以按照我的方法做到这一点。如果你需要用'function3()'中获得的数据做一些东西,只需订阅它,然后在'subscribe()'... – SrAxi

相关问题