Muirik
Muirik

Reputation: 6289

My "this.router.navigate" Doesn't Trigger in my Angular 2 App

I have a function that does a post request to the API, and gets back an object for a newly created document. I am successfully getting data back from the API in this function call, but while I am getting a new object with the correct "_id" info logged to the console, my "this.router.navigate(['/record', this._id])" is not triggering. I assume I should be able to tack it onto the end of this function like I am doing, so that it programmatically handles the navigation when the data is returned. But it's not working. The app doesn't navigate at all when that function is triggered. What am I missing here?

createRecord() {
        this.recordsService.createRecord().subscribe(
        data => {
            // refresh the list
            console.log(data);
            return true;
        },
        error => {
            console.error("Error creating record...");
            return Observable.throw(error);
        }
        );
        console.log('createRecord function initiated...');
        this.router.navigate(['/record', this._id]);
    }

My service looks like this:

    createRecord() {
        const headers = new Headers({ 'Content-Type': 'application/json' });
        const options = new RequestOptions({ headers: this.headers });
        const body = JSON.stringify({deleted: true});
        return this._http.post
        ('https://api.somesite.com/v0/records?apikey=someapikey',
        body, options).map((res: Response) => res.json());
   }

Upvotes: 0

Views: 393

Answers (1)

mickdev
mickdev

Reputation: 2885

Actually, you should call router.navigate when you successfully get your data (in the success callback)

createRecord() {
        this.recordsService.createRecord().subscribe(
        data => {
            // refresh the list
            this.router.navigate(['/record', data._id]);
        },
        error => {
            console.error("Error creating record...");
            return Observable.throw(error);
        }
        );
    }

Upvotes: 1

Related Questions