当模型值更改时,HTML不会更新

时间:2018-08-02 07:09:43

标签: angular typescript angular5

在我当前的项目中,需要一个组件来显示不同表中的值,具体取决于菜单项的单击。

我正在对 Units Colors 模块使用Observable且使用相同的组件。

1)在第一秒中,如果我先单击“单位”,它将正常工作并在网格中绑定正确的数据。 enter image description here

2)在第二个窗口中,如果我单击“颜色”,则应更新网格数据。但是它没有更新,甚至没有调用服务器的控制器或API调用。 enter image description here

已经尝试过:实现了changeDetectorRef和ngDoCheck东西,但是没有运气。

这是我的代码组件

export class ListMasterMainComponent implements OnInit
{
    masterModels: MasterMainModel[];
    masterModel = new MasterMainModel();
    errorMessage: string;
    url: string;
    @Input() message: string;
    previous;
    constructor(private _ref: ChangeDetectorRef, private data: DataService, private el: ElementRef, private router: Router, private MasterMainService: MasterMainService) { }

    ngOnInit()
    {
        this.previous = this.message;
        this.data.currentMessage.subscribe(message => this.message = message)
        /* Message field will be changed according to selected menu Units in case of 
        Units and Colors in case of Colors.*/
        this.fetchData();
    }

    ngDoCheck()
    {
        if (this.previous !== this.message)
        {
            this._ref.detectChanges();
        }
    }

    onClickAddMasterMain(moduleText)
    {
        this.data.changeMessage(moduleText)
        this._ref.detectChanges();
        const url = this.el.nativeElement.href;
        this.router.navigate(['/addeditmaster'], {
            skipLocationChange: true,
        })
    }

    fetchData(): void
    {
        this.MasterMainService.getDataWithObservable()
            .subscribe(masterModels => this.masterModels = masterModels,
                error => this.errorMessage = error);
    }
}

对于菜单项,单击

onClickMainMasters(message)
{
    this.data.changeMessage(message)

    switch (this.message)
    {
        case 'Colors':
        this.data.changeUrl('http://localhost:64599/api/Colors');
        this.data.currentUrl.subscribe(url =>this.url=url)
          this.router.navigate(['/listmaster'], {
            skipLocationChange: true,
        });

        event.preventDefault();
        break
        case 'Units':
        this.data.changeUrl('http://localhost:64599/api/Units');
        this.data.currentUrl.subscribe(url =>this.url=url)
          this.router.navigate(['/listmaster'], {
            skipLocationChange: true,
        });
        event.preventDefault();
        break
    }

感谢您的帮助。谢谢。

1 个答案:

答案 0 :(得分:0)

从我看到的内容来看,您将再次导航到相同的url /组件/listmaster,但是如果activeRoute不变,则不会重新加载该组件。如果显示正确的数据取决于在fechtData()的{​​{1}}中调用的ngOnInit函数,则必须确保再次实例化此组件或再次调用ListMasterMainComponent其他地方。

查看此问题:Angular 2 router navigate not working 2nd time with the same url

我的回答是:https://stackoverflow.com/a/51540703/9423231