【问题标题】:Fetch additional data when ngIf condition is satisfied满足 ngIf 条件时获取附加数据
【发布时间】:2016-03-22 21:28:29
【问题描述】:

我有两个简单的组件。一个用于列出用户,第二个用于详细视图。

当我选择一个特定的用户时,这个用户绑定到一个变量 selectedUser,ngIf 详细组件得到满足,我想提出额外的请求来获取更多与这个用户相关的数据。

实现这一点的适当方法是什么?当我制作自定义 ngIf 函数时,它开始向我的 api 发出大量请求,但我只需要一次。谢谢!

这是我的代码:

@Component({
    selector: 'users',
    template: `
        <div *ngFor="#user of users"
            (click)="onSelect(user)">
                {{ user.name }}
        </div>
        <user-detail [user]="selectedUser"></user-detail>
    `
export class UserComponent {
    onSelect(user: IUser) {
        this.selectedUser = user;
    }
}

@Component({
    selector: 'user-detail',
    template: `
        <div *ngIf="user">
            {{ user.name }} {{ user.id }}
            <div *ngFor="task of tasks"> <-- this is what i actually try to fetch
            </div>
        </div>
`

export class UserDetailComponent {
    @Input() user: IUser[];
}

【问题讨论】:

    标签: angular


    【解决方案1】:

    我建议您使用 ngIf 指令而不是 user-detail 组件使用。然后,您可以在 user-detail 组件中使用 ngDoCheck 和 ng 挂钩,以在 user 的 Input 值发生更改时触发期望代码。

    <user-detail *ngIf="selectedUser" [user]="selectedUser"></user-detail>
    

    组件

    @Component({
        selector: 'user-detail',
        template: `
            <div>
                {{ user.name }} {{ user.id }}
                <div *ngFor="task of tasks"> <-- this is what i actually try to fetch
                </div>
            </div>
    `
    
    export class UserDetailComponent implements DoCheck {
        @Input() user: IUser[];
    
        ngDoCheck(){
           //stuff which will fireup when everytime component user gets changed.
        }
    }
    

    【讨论】:

    • 是的,它有效!当条件满足时,组件被初始化。但是当我更改选定的用户时,它不会再次初始化。我应该在这里使用 ngOnChanges 吗?我可以以某种方式缓存结果吗?
    • @v01d 所以ngDoCheck 将是合适的而不是ngOnInit
    【解决方案2】:

    您可以将 ng-if 与作用域函数一起使用。只要返回 true 或 false,就可以在那里进行验证,也可以拉取额外的数据。

    类似的东西(在 javascript 中):

    var busy = false;
    scope.Validate = function() {
           //Do validation
           if(/*condition*/) {
             if(!busy) {
                 busy = true;
                 /*Do your fetch for data and set busy = false when done*/
             }
             return true;
           }
           else return false; 
    }
    

    然后在元素中调用ng-if="Validate()"

    【讨论】:

    • 你也可以用javascript做角度
    • 感谢您告诉我.. :D
    • 是的,对于 javascript 中的 angular 2,文档仍然没有显示太多,但它就在那里。
    猜你喜欢
    • 2020-12-18
    • 2018-10-06
    • 1970-01-01
    • 2019-05-13
    • 1970-01-01
    • 2018-03-20
    • 1970-01-01
    • 2011-07-12
    • 2014-09-02
    相关资源
    最近更新 更多