A. Gladkiy
A. Gladkiy

Reputation: 3450

Error handling stop propagation after router.navigate Angular 2

I've implemented error handling on server side to return json. And now I'm working on error handling in Angular 2.

My component is:

onClick() {
        this.dataService.getData()
            .subscribe((response: Json) => {
                console.log("some text");
                if(response.status !== 'fail') {
                    ...
                }
            });
    }

My DataService.ts is:

getData(): Observable<Json> {
        return this.http
            .get(this.getDataUrl)
            .map((response: Response) => {
                return this.responseService.extractJson(response);
            })
            .catch(error => {
                return this.errorService.handleError(error);
            });
    }

And ResponseService.ts:

extractJson(response: Response): any {
        let json: Json = response.json();
        if (json.status === 'success') {
            return json;
        } else {
            this.router.navigate(['something-went-wrong']);
            return null;
        }
    }

But app continues to execute code further in subscribe section, so I see in browser console some text and error Cannot read property 'status' of null. How can I stop further propagation after router.navigate? What should I do or return after router.navigate for that?

Upvotes: 2

Views: 1828

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 658205

You return null in extractJson therefore you can just

onClick() {
    this.dataService.getData()
        .subscribe((response: Json) => {
            console.log("some text");
            if(!response) {
              // do nothing or whatever
              return
            }
            if(response.status !== 'fail') {
                ...
            }
        });
}

update
Use filter to prevent the null to be event emitted as an event:

getData(): Observable<Json> {
    return this.http
        .get(this.getDataUrl)
        .map((response: Response) => {
            return this.responseService.extractJson(response);
        })
        .catch(error => {
            return this.errorService.handleError(error);
        }).filter(val => val != null);
}

Upvotes: 2

Related Questions