代码之家  ›  专栏  ›  技术社区  ›  DarkW1nter

角度6-尝试将函数传递给另一个类中的函数

  •  0
  • DarkW1nter  · 技术社区  · 6 年前

    我有一个表,在其中单击行上的按钮以更新行上的bool字段。 然后我想刷新表。 以下是:

    editItem—进行调用并更新项,但我希望它随后运行传入的函数,这是下面的最后一个函数getItems,它将重新填充表所基于的对象。

    它在editItem的最后一行失败

    TypeError: getItems is not a function
    

    有人能告诉我我做错了什么吗?

    SaveItem(flag: boolean) {
        this.item$.Published = flag;
        this.edit.editItem(this.item$, this.id, this.getItems(this.items$));
      }
    
    
    editItem(item, id, getItems) {
        const url = this.apiUrl + '/tables/Items/' + id
        this.http.patch(url, item, httpOptions).subscribe((data) => getItems(data));
      }
    
    
    getItems(itemList: Item[]): void{
      this.data.getItems()
      .subscribe(data => this.items$ = data);
    }
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Juan M. Medina    6 年前

    必须将回调声明为平面函数,而不是函数的结果。看到这个小道消息了吗,可以在Typescript草稿行上运行 by clicking here . 我确实提出了一些意见,比如“/”这是一个重要的变化“在这里适用。

    class Item {
        Published: boolean
    }
    
    class Observable {
        subscribe(callback: (data: Array<Item>) => any) {
            callback(new Array<Item>());
        }
    }
    
    class Test {
    
        apiUrl: string;
        http = {
            patch: (url, item, httpOptions) => { 
                return new Observable();
            }
        };
        item$ = new Item();
        items$: Item[];
        id: 'someid';
        edit = {
            editItem: (item: any, id: string, callback: (data: Item[]) => void) => {
                // THIS IS THE IMPORTANT CHANGE
                return this.editItem(item, id, callback);
            }
        }
        data = {
            getItems: () => { 
                return new Observable();
            }
        };
    
        editItem(item, id, getItems) {
            const httpOptions: any = {};
            const url = this.apiUrl + '/tables/Items/' + id
            this.http.patch(url, item, httpOptions).subscribe((data) => this.getItems(data));
        }
    
        getItems(itemList: Item[]): void {
            this.data.getItems()
                .subscribe(data => { this.items$ = data; alert("Hey! I got called"); });
        }
    
        SaveItem(flag: boolean) {
            this.item$.Published = flag;
            // THIS IS THE IMPORTANT CHANGE
            this.edit.editItem(this.item$, this.id, this.getItems);
        }
    }
    
    let test = new Test();
    test.SaveItem(true);
    
    推荐文章