【问题标题】:Angular 2 view not updating after I update a record in the database更新数据库中的记录后,Angular 2 视图未更新
【发布时间】:2016-08-31 19:35:11
【问题描述】:

我有一个使用 Angular 2 的简单 CRUD 应用程序。主页显示用户可以创建、编辑或删除的卡片列表。

在卡片编辑页面上,当我点击提交时,它会这样调用:

card-edit.component.ts

onSubmit() {
        this.updateCard(this.card);

        alert("Card updated!");        
        this._router.navigate(['/CardList']);
    }

updateCard(updatedCard: Card) {
        // call to card.service.ts
        this._cardService.updateCard(updatedCard)
            .subscribe(
            result => this.response = result,
            error => this.errorMessage = <any>error);
    }

card.service.ts

updateCard(updatedCard: Card): Observable<string> {
        let body = JSON.stringify(updatedCard);
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });

        return this._http.put(this._cardUrl + "/" + updatedCard.id, body, options)
            .map(this.extractData)
            .catch(this.handleError);
    }

卡在数据库中更新。然后路由器带我回到卡片列表。

card-list.component.ts

import { Component, OnInit} from 'angular2/core'
import { ROUTER_DIRECTIVES } from 'angular2/router'

import { Card } from './card'
import { CardService } from './card.service'
import { CardFilterPipe } from './card-filter.pipe'


@Component({
    templateUrl: 'app/card/card-list.component.html',
    directives: [ROUTER_DIRECTIVES],
    pipes: [CardFilterPipe]
})

export class CardListComponent implements OnInit {
    pageTitle: string = 'Card List';
    cards: Card[];
    errorMessage: string;
    listFilter: string;

    constructor(private _cardService: CardService) { }

    ngOnInit(): void {
        this.getCards();   
    }

    getCards() {
        this._cardService.getCards()
            .subscribe(
            result => this.cards = result,
            error => this.errorMessage = <any>error);
    }

}

问题:我刚刚在编辑页面所做的更改没有反映在列表视图中。需要刷新整页才能让记录反映最新数据。

【问题讨论】:

    标签: angular rxjs observable angular2-routing angular2-template


    【解决方案1】:

    我想我明白了。看起来我必须在 updateCard() 而不是 onSubmit() 中调用路由器导航。

    updateCard(updatedCard: Card) {
            // call to service to update record in database
            this._cardService.updateCard(updatedCard)
                .subscribe(
                result => this.response = result,
                error => this.errorMessage = <any>error,
                () => this._router.navigate(['CardList'])
                );
    }
    

    【讨论】:

      猜你喜欢
      • 2017-09-07
      • 1970-01-01
      • 2017-08-28
      • 1970-01-01
      • 1970-01-01
      • 2017-05-18
      • 1970-01-01
      • 2017-02-28
      • 2017-10-03
      相关资源
      最近更新 更多