简体   繁体   中英

Angular 2 / 4 toPromise works but I am having trouble with Observables

I'm trying to wrap my head around Observables

Here is what currently works for me with the .toPromise

request.ts

get(url): Promise<any>
{
    //  HARD CODED A URL I FOUND , NOT USING THE "url" param
    return this.http.get("https://conduit.productionready.io/api/profiles/eric").map(response => {
        return response.json() || {success: false, message: "No response from server"};
    }).catch((error: Response | any) => {
        return Observable.throw(error.json());
    }).toPromise();
}

That works,

Called from

event.service.ts

function ...

this.Request.get("/user").then(response => {
        console.log("Got response:", response);
    }).catch(error => {
        console.log("Got error:", error);
    }).then(response => {
        console.log("Another response:", response);
    }).catch(error => {
        console.log("Got another error:", error);
    });

Instead what I WANT TO BE DOING is Observables

So

I try to "subscribe"

Subscriber

I don't really understand how to use "data" and "subscribe" etc..

 var url = "https://conduit.productionready.io/api/profiles/eric";
    var blah;
    this.getDataObservable(url).subscribe(
         data => {
             blah = data;
             console.log("I CANT SEE DATA HERE: ", blah);
         }
     );

Function to call

getDataObservable(url: string) {
    return this.http.get(url)
        .map(data => {
            data.json();
            // the console.log(...) line prevents your code from working 
            // either remove it or add the line below (return ...)
            console.log("I CAN SEE DATA HERE: ", data.json());
            return data.json();
        });
}

There are many examples of how to do this ... here is one:

SERVICE

getProducts(): Observable<IProduct[]> {
    return this._http.get(this._productUrl)
        .map((response: Response) => <IProduct[]> response.json())
        .do(data => console.log('All: ' +  JSON.stringify(data)))
        .catch(this.handleError);
}

private handleError(error: Response) {
    // in a real world app, we may send the server to some remote logging infrastructure
    // instead of just logging it to the console
    console.error(error);
    return Observable.throw(error.json().error || 'Server error');
}

COMPONENT

ngOnInit(): void {
    this._productService.getProducts()
            .subscribe(products => this.products = products,
                       error => this.errorMessage = <any>error);
}

NOTE: This is using the original Http service and not the new HttpClient service.

To understand this code, you need to understand Observables and how Http works. I would highly recommend reading the documentation at Angular.io, working through the tutorial at angular.io, or watching a course such as this one: https://app.pluralsight.com/library/courses/angular-2-getting-started (you can sign up for a free week to watch.)

Your service should be like this.So you can subscribe in component

getDataObservable(url: string) {
    return this.http.get(url).map(data =>  data.json()).catch(error=>Observable.throw(error));
}

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