简体   繁体   English

Angular 2:从promise调用函数时视图不会更新

[英]Angular 2 : View doesn't update when function is called from promise

My angular is pretty basic. 我的角度很基本。 I have a view where I display an object (which is in a service): 我有一个显示对象的视图(在服务中):

<div *ngFor="let group of service.groups">
    {{group.id}} - {{group.name}}
</div>

The simple version of my service looks like this: 我的服务的简单版本如下所示:

public pushNewGroup(group) {

    this.groups.push(group);
    console.log('Pushing new group!');

    // this.zone.run(() => {
    //     this.groups.push(group);
    // });

}

public addGroup(group: Group) {
    let component = this;
    this.api.postWrapper('groups', group).then(function (data: Group) {
        component.pushNewGroup(data);
    });
}

If I create a button to call the service, everything works and the view updates: 如果我创建一个按钮来调用该服务,则一切正常,视图将更新:

<input type="button" (click)="pushGroup()" value="Add group/>

With service call in the view component: 在视图组件中使用服务调用:

pushGroup() {
    let group = { ... }
    this.service.pushNewGroup(group);
}

But if I call the promise through a dialog window then it doesn't update the view: 但是,如果我通过对话框窗口调用promise,那么它不会更新视图:

<li (click)="addGroup()" ><a>Add Group</a></li>

Component (simplified): 组件(简体):

addGroup() {
    let dialogRef = this.dialog.open(AddGroupComponent, {
        data: {
            ...
        },
    });
}

export class AddGroupComponent {

    constructor(private service: service) {}

    addGroup(group: Group) {
        this.service.addGroup(group);
    }
}

I've tried both ngZone and ChangeDetectionStrategy.Default. 我已经尝试了ngZone和ChangeDetectionStrategy.Default。 Both solutions did not work for me. 两种解决方案都不适合我。 I can see that the object changes both times and the console log also works. 我可以看到对象同时更改了两次,并且控制台日志也起作用。 But the view does not update. 但是视图不会更新。


My @Componment doesn't have anything interesting. 我的@Componment没有任何有趣的东西。 For the whole class it's: 对于整个班级来说:

@Component({
    templateUrl: './mainComponent.html',
    styleUrls: ['./mainComponent.scss'],
    providers: []
})

And for my add group dialog it is: 对于我的添加组对话框,它是:

@Component({
    selector: 'addGroup',
    templateUrl: './AddGroupComponent.html',
    styleUrls: ['./AddGroupComponent.scss'],
    providers: [ApiService, PermissionsService, Service],
    changeDetection: ChangeDetectionStrategy.Default
})

EDIT: It's very hard to extract the whole thing into plunker, but I tried recreating it and turns out the promise thing works. 编辑:很难将整个内容提取到plunker中,但是我尝试重新创建它并证明诺言功能有效。 I think the fault might be with MatDialog. 我认为故障可能出在MatDialog上。 It doesn't update the main view. 它不会更新主视图。 I tried recreating the whole thing in plunker, but I can't get angular material working in plunker. 我尝试在plunker中重新创建整个内容,但无法在plunker中工作。 And it seems like all other examples on the net are broken as well: 似乎网上所有其他示例也都被破坏了:

https://embed.plnkr.co/LTAEwV6bNvoGQAFoky60/ https://embed.plnkr.co/LTAEwV6bNvoGQAFoky60/

Why don't you use arrow function and forget this hack let component = this ? 为什么不使用箭头功能而忘记此hack let component = this Maybe this can be the problem. 也许这可能是问题所在。 Use the ES6 features, follow the angular styleguide. 使用ES6功能,并遵循角度样式指南。

public addGroup(group: Group) {
  this.api.postWrapper('groups', group).then( (data: Group) => {
     this.pushNewGroup(data);
  });
}

Promise will postpone the change detection to the next detection cycle. Promise会将更改检测推迟到下一个检测周期。

Try this: 尝试这个:

Add private _cdr: ChangeDetectorRef in the constructor.(obviously import ChangeDetectorRef ) 在构造函数中添加private _cdr: ChangeDetectorRef 。(显然,导入ChangeDetectorRef

Add this._cdr.detectChanges() inside promise (at the end). 在promise的末尾添加this._cdr.detectChanges() )。

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

相关问题 在Angular中关闭FullScreen时不会调用转义函数 - Escape Function Doesn't Get Called When Close FullScreen in Angular Angular 10 - 修改 model 时视图不更新 - Angular 10 - View doesn't update when model is modified 角。 来自另一个组件更新模型的组件的调用方法,但不要更新被调用组件的视图 - Angular. Calling method of component from another component update model, but don't update the view of called component Angular 不更新数组推送视图 - Angular doesn't update view on array push 订阅不会更新 Angular 中的视图 - Subcribe doesn`t update view in Angular 从Promise Angular4内部更新视图中的变量 - Update variable in view from inside promise Angular4 Angular updateTag函数不会更新源代码视图HTML中的元标记 - Angular updateTag function doesn't update meta tag in source view HTML ActivatedRoute的Angular承诺不适用于Typescript await - Angular promise from ActivatedRoute doesn't work with Typescript await User.FindFirst(ClaimTypes.NameIdentifier) 从前端调用时不检索任何内容(Angular) - User.FindFirst(ClaimTypes.NameIdentifier) doesn't retrieve anything when called from frontend (Angular) 从angular2中的按钮元素调用router.navigate时不起作用 - router.navigate doesn't work when called from button element in angular2
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM