2016-12-05 203 views
0

嘿傢伙我想知道如何從2個方法中訪問全局範圍(this)中的變量。幫助讚賞從方法Typescript訪問全局變量

location: any; 

    doSomethingOne() { 
    Geolocation.getCurrentPosition().then((resp) => { 
       this.location = resp; 
       this.doSomething(); 

      }).catch((error) => { 
       console.log('Error getting location', error); 
      }); 
    } 

    doSomething() { 
     return new Promise(resolve => { 
     this.http.get('http://xxxxxxxxx.xxxx/api/' + this.location.coords.latitude + '/' + this.location.coords.longitude + '/5') 
      .map(res => res.json()) 
      .subscribe(data => { 
       this.data = data; 
       resolve(this.data); 
      }); 
    }); 
    } 

如何從Promise中訪問this.location?控制檯顯示 '未定義' 訪問它

+2

'this'不是全局作用域時。 '窗戶'是。如果你想獲得* object *作用域,箭頭函數作爲'then'回調應該這樣做。 – estus

回答

0

試試這個

doSomethingOne(): Observalbe<any> { 
    Geolocation.getCurrentPosition().then((resp) => { 
       return new Promise(resolve => { 
     return this.http.get('http://xxxxxxxxx.xxxx/api/' + resp.coords.latitude + '/' + resp.coords.longitude + '/5') 
      .map(res => res.json()) 
      .subscribe(data => { 
       this.data = data; 
       return resolve(this.data); 
      }); 
     }); 

      }).catch((error) => { 
       console.log('Error getting location', error); 
      }); 
    }