简体   繁体   English

Angular 2 - * ngif在从oberservable subscribe进行变量更新时不刷新

[英]Angular 2 - *ngif not refreshing when variable update from oberservable subscribe

in the html i have warning should only be shown when a error state occurs like thius 在html中我有警告只应在出现像thius这样的错误状态时显示

<div class="alert alert-danger" *ngIf="error">
    <strong>Not saved!</strong> There was an error when saving the project. Please try again later.
</div>

this works fine. 这很好用。 but when I set the value from a observable the ngIf doesn't get the updated value. 但是当我从一个observable设置值时,ngIf没有得到更新的值。

Here the simplified code which always sets error to true for testing purposses 这里是简化的代码,它始终将错误设置为true以用于测试目的

export class createProjectComponent {
    constructor(private service:ProjectsService){

    }

    model = new myModel();
    error = false;
    submitForm(){    
        this.service.createProject(this.model).subscribe(i=>{
            this.error=true;
          }
    }

is there some kind of notification i have to trigger? 有什么样的通知我必须触发?

You can try if this fixes your issue: 如果这可以解决您的问题,您可以尝试:

constructor(private cdRef:ChangeDetectorRef) {}

submitForm(){    
    this.service.createProject(this.model).subscribe(i=>{
        this.error=true;
        this.cdRef.detectChanges();
    }
}

If it does there is some code in this.service.createProject(this.model) that causes execution leaving Angulars zone. 如果确实存在,则this.service.createProject(this.model)中会有一些代码导致执行离开Angulars区域。

update 更新

You don't need this if you use ()=> everywhere instead of function () and if you don't pass functions just by name like someFunc(mycallback) but instead with someFunc(() => mycallback()) or someFunc(mycallback.bind(this)) 你不需要这个,如果你使用()=>到处而不是function () ,如果不是像someFunc(mycallback)那样通过名称传递函数,而是使用someFunc(() => mycallback())someFunc(mycallback.bind(this))

Found the error. 发现错误。 the this changes . this改变了。 in the observe this points to the osbervable not anymore to the component. 在观察中, this指向osbervable不再是组件。

so I have to get a reference of the component to a variable and set error on this reference to true. 所以我必须得到一个变量的组件引用,并将此引用的错误设置为true。

working code looks like this: 工作代码如下所示:

var component = this;

this.service.createProject(this.model).subscribe(i=>{
                component.error = true;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM