可观察订阅 http.get

Observable Subscribe in http.get

我在 http.get 中将字符串 'MyAddressConfig' 转换为 return 有点麻烦。它从 Ionic2 Storage 获取数据。问题是我不断收到

GET http://localhost:0000/[object%20Object]my/path?&tst=1 404 (Not Found)

有什么想法吗? -谢谢

我的地址配置

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/'
        });
    }

我的服务

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); 
    }

您的 MyConfig.GetRestAddress() 不是 return 字符串,它 return 是对象。 [object%20object] 是你从 MyConfig.GetRestAddress() because your object is parsed to a string

得到的

这是因为GetRestAddress()return订阅了。这样的东西就是你想要的:

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); 
}