简体   繁体   中英

Observable Subscribe in http.get

Im have a bit of trouble getting 'MyAddressConfig' to return a string in my http.get . It gets the data from Ionic2 Storage. The problem is that I keep getting

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

Any ideas? -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); 
    }

Your MyConfig.GetRestAddress() does not return a string, it return an object. [object%20object] is what you get from MyConfig.GetRestAddress() because your object is parsed to a string

This is because GetRestAddress() return a subscription. Something like this is what you want:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM