Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling success, error callbacks using subscribe in angular2?

Giving responce.json () is not function for my case

component.ts

 this.AuthService.loginAuth(this.data).subscribe(function(response) {
  console.log("Success Response" + response)
},
  function(error) {
  console.log("Error happened" + error)
},
  function() {
  console.log("the subscription is completed")
});

AuthService.ts

     loginAuth(data): Observable<any> {
  return this.request('POST', 'http://192.168.2.122/bapi/public/api/auth/login', data,{ headers:this. headers })
      .map(response => response)
      //...errors if any
      .catch(this.handleError);
  }

Giving [object,objet] If I put map function service like .map(response => response.json()) is giving error like responce.json () is not function

Please help me

like image 613
Runali Avatar asked Feb 13 '17 11:02

Runali


People also ask

What is subscribe callback in angular?

What is the subscribe callback in Angular? An Observable is the main tool provided by the RxJS library whose Angular uses extensively. As with a regular JavaScript Promise, the goal of an Observable is to handle asynchronous events. The key difference between an Observable and a Promise is that Observables are lazy.

How to trigger HTTP calls in angular?

Now, we will trigger HTTP calls in Angular by using Promises and handle the Success and Error callbacks. Open the app.module.ts file then import the HttpClientModule and update the imports array. The HttpClientModule is required to trigger HTTP calls from the Angular applications .

Is it OK to subscribe to components in angular?

It’s ok to subscribe When some components, for example, AppComponent and most of the services (with exception of services from lazy loaded modules and services provided in @Component decorator) in our Angular application will be instantiated only once during the application startup.

Does angular use RxJS?

Angular embraces RxJS and the reactive programming paradigm. As Angular developers, we really should be doing the same. This article will be very opinionated, so comments or questions are more than welcome. What is the subscribe callback in Angular? An Observable is the main tool provided by the RxJS library whose Angular uses extensively.


2 Answers

In your service page

//Import if needed

import { Observable } from 'rxjs/Observable';    
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';

let options = new RequestOptions({ headers: this.headers });
return this.http.post('http://192.168.2.122/bapi/public/api/auth/login', data, options)
.map((res: Response) => {
    return { "res": res.json() };
})
.catch((e: any) => {
    console.log(e.status);
    return Observable.throw({"Errors":e.json()});
});

And your template ts file

this.AuthService.loginAuth(this.data).subscribe((result: any) => {
    let res = result.res;
    console.log(res)
},(error: any) => {
    if(typeof error['Errors'] !="undefined"){
        console.log(error['Errors']);
    }
});

It's working for me perfectly

like image 137
bipin patel Avatar answered Dec 12 '22 18:12

bipin patel


Try using this structure:

this.AuthService.loginAuth(this.data).subscribe(
        suc => {
            console.log(suc);
        },
        err => {
            console.log(err );
        }
    );

Also you might want to stringify your data being sent to the server such as:

loginAuth(data) {
    var headers = new Headers();
    headers.append('Content-Type', 'application/json');
    var info = JSON.stringify(data);

    return this._http.request("http://192.168.2.122/bapi/public/api/auth/login", info , { headers: headers }).map(res => res.json())
}

And you must declare a variable in the constructor of your service referencing Http like such:

import { Http, Headers, Response, URLSearchParams } from '@angular/http';    
constructor(private _http: Http) {
}

This is the way it worked for me

like image 42
Rossco Avatar answered Dec 12 '22 17:12

Rossco