在http.get中观察订阅

时间:2017-03-10 20:03:29

标签: angular typescript ionic2 storage observable

我在使用MyAddressConfig'时遇到了一些麻烦。在我的http.get中返回一个字符串。它从Ionic2 Storage获取数据。问题是我一直在

  

获取http://localhost:0000/[object%20Object]my/path?&tst=1 404(未找到)

有什么想法吗? -Thanks

MyAddressConfig

GetDataFromStorage: Observable<any> =

Observable.fromPromise(
    Promise.all([
        this.ionicStorage_.get('MyRestIPAddress'), // 'localhost'
        this.ionicStorage_.get('MyRestIPPort'), // '0000'
    ])
        .then(([val1, val2]) => {
            this.MyRestIPAddress = val1;
            this.MyIPPort = val2;
            return [val1, val2];
        })
);

 GetRestAddress() {
        return this.GetDataFromStorage.subscribe(([val1, val2]) => { // 'localhost','0000'
           let RestAddress = 'http://' + val1 + ':' + val2 + '/rest/';
           console.log(RestAddress);
           return RestAddress;  // 'http://localhost:0000/rest/'
        });
    }

为MyService

getStoresSummaryResults(): Observable<MyTypeClass> {
        let MyConfig: MyAddressConfig;
        MyConfig = new MyAddressConfig(this.ionicStorage_);

        return this.http_.get(MyConfig.GetRestAddress() + 'my/path?&tst=1')
            .map(res => res.json()) 
            .catch(this.handleError); 
    }

1 个答案:

答案 0 :(得分:6)

你的MyConfig.GetRestAddress()没有返回字符串,它会返回一个对象。 [object%20object]是您从MyConfig.GetRestAddress() because your object is parsed to a string

获得的

这是因为GetRestAddress()返回订阅。这样的事情就是你想要的:

GetRestAddress() { //return the url as Observable
    return this.GetDataFromStorage.switchMap(([val1, val2]) => { 
       let RestAddress = 'http://' + val1 + ':' + val2 + '/rest/';
       return Observable.of(RestAddress);  // 'http://localhost:0000/rest/'
    });
}


getStoresSummaryResults(): Observable<MyTypeClass> {
    let MyConfig: MyAddressConfig;
    MyConfig = new MyAddressConfig(this.ionicStorage_);

    return MyConfig.GetRestAddress()
        .switchMap(url => this.http_.get(url + 'my/path?&tst=1')
        .map(res => res.json()) 
        .catch(this.handleError); 
}