2017-05-01 4 views
0

J'ai du mal à trouver comment avoir toastr dans ma fonction handlerError. Lorsque je l'exécute l'erreur que je reçois estComment ajouter Toastr dans la fonction de capture http?

'erreur' undefined

Voici mon code

private handlerError(error: any) { 

    var errorMessage = 'Server error'; 

    this.toastrService.error(errorMessage); <-- This doesn't work 

    return Observable.throw(errorMessage); 
} 

il est appelé comme

post(url, data): Observable<any> {  
    this.toastrService.error('hey'); // <-- This works 
return this.http.post(CONSTANT.API_URL + url, data, { 
    headers: this.createAuthorizationHeader() 
}). 
    map((res:Response) => { return this.toCamel(res.json()) }). 
    catch(this.handlerError); 
} 

Toastr est injecté

constructor(private http: Http, private toastrService: ToastrService) {} 

Répondre

1

changement

catch(this.handlerError); 

à

catch(error => this.handlerError(error)) 

Lorsque vous appelez comme this.handlerError votre cet objet dans la méthode handlerError est la fenêtre

Lorsque vous faites erreur => this.handlerError (erreur) - cette erreur vous renvoie à votre instance de classe.

Il s'agit d'un comportement javascript standard.

class A { 
    classAContext() { 
    return()=>this.fn(); 
} 

windowContext() { 
    return this.fn; 
    } 

fn() { 
    console.log(this); 
} 
} 

nous allons créer un objet:

let a = new A(); 

cette ligne affichera la fenêtre

a.windowContext()(); 

cette ligne affichera A {}

a.classAContext()(); 
+0

qui est si bizarre. Thanx – Demodave

+0

j'ai ajouté une explication supplémentaire –