简体   繁体   中英

Observable and dependency injection in angular2

I have a service in like an this:

@Injectable()
export class AuthService {

    private contentHeader: Headers = new Headers({"Content-Type": "application/json", "Accept": "application/json"});   

    constructor(public events: Events, private authHttp: AuthHttp){

    }

    public get(url): Observable<any> {            
        return this.authHttp.get(url, { headers: this.contentHeader })
            .map(this.extractData)
            .catch(this.handleError);
    }


    public extractData(res: Response) {
        try {
            let body = res.json();
            return body || {};
        }
        catch (e) {
            return {};
        }
    }

    public handleError(error: any) {
        if (error.status == 401 || error.status == 403)
        {
            // injected
            this.events.publish('user:logout');
        }

        return Observable.throw(error);
    }

}

this.events not work inside of handleError and trigger this error in console: EXCEPTION: TypeError: this.events is undefined

How can i use my services with dependency injection inside of map and catch section of Observable?

You need to use arrow function to retain context

.catch((err) => this.handleError(err));

or

public handleError = (error: any) => {
  ...  
}

or use bind method

.catch(this.handleError.bind(this));

See more details about lexical this here:

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