传递给服务函数后未定义角度变量/对象

时间:2018-11-14 22:04:24

标签: json angular

我有以下代码。

Detail.component.ts

ngOnInit() {
    this.route.paramMap.subscribe((params) => {
                const itemId = params.get('itemId') //works
                console.log(itemId)
                if (itemId === 'new') {
                    this.mode = 'new'
                    this.item = new Item()
                } else {this.shoppingListService.getSingleItem(itemId).then((recItem) => {
                        this.item = recItem
                        console.log(JSON.stringify(this.item)); // works
                    })
                }
            })
}

以下功能在Detail.component.html

中触发

在调用服务调用(updateItem或editItem)之前,该对象仍已定义!

     async onSaveClicked() {

    console.log("inside onsaveClicked" + JSON.stringify(this.item)); //works

            try {
                if (this.mode === 'new') {
                    this.shoppingListService.createItem(this.item)
                    this.router.navigate(['/list'])

                } else if (this.mode === 'edit') {
                    this.shoppingListService.updateItem(this.item)
                    console.log("edit: " + JSON.stringify(this.item));



                    this.mode = 'view'
                }
            } catch (error) {
                console.log(error)
            }
}

以下服务功能称为

在此函数中,传递的对象(updateItem)未定义。

async updateItem(updateItem: Item) {

    console.log("inside update Item " + updateItem.id) //undefined
    const result = await this.httpClient.put<any>(`${this.apiEndpoint}/${updateItem.id}`, updateItem).toPromise()
    return result;      
}

必须做某事。 httpclient的异步行为,但是问题出在哪里呢?

0 个答案:

没有答案