我和#34; this.router.navigate"不在我的Angular 2应用程序中触发

时间:2017-03-02 19:47:22

标签: javascript angular

我有一个函数可以对API发出请求,并获取新创建文档的对象。我在这个函数调用中成功地从API获取数据,但是当我得到一个具有正确" _id"的新对象时信息记录到控制台,我的" this.router.navigate([' / record',this._id])"没有触发。我假设我应该能够将其添加到此函数的末尾,就像我正在做的那样,以便在返回数据时以编程方式处理导航。但它不起作用。当触发该功能时,应用程序根本无法导航。我在这里缺少什么?

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]);
    }

我的服务如下:

    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());
   }

1 个答案:

答案 0 :(得分:1)

实际上,你应该在成功获取数据时调用router.navigate(在成功回调中)

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);
        }
        );
    }
相关问题