網站搜尋

javascript - 在 Angular 中將 Promise 從一個服務調用傳遞到另一個服務調用


所以我有一個服務調用發送到後端並保存一個對象,這個調用設置了一個 promise 來返回一個數字。

那個通話看起來是這樣

    saveTcTemplate(item: ITermsConditionsTemplate): ng.IPromise<number> {
        item.modifiedDate = new Date();
        return this.$http.post(this.api + '/SaveTcTemplate', item)
            .then(this.returnData); 
    }

    returnData = (response: any) => {
        return response.data;
    };

這是在創建新物件時,所有欄位都設置為所需的值,然後傳遞以保存,再調用以顯示。

這是用來在物件被儲存後提取該物件的 get 函數。

    getTermsConditions(id: number): ng.IPromise<ITermsConditionsTemplate> {
        return this.$http.get(this.api + '/GetTermsConditions',
            {
                params: {
                    id: id
                }
            }).then(this.returnData);
    }

這是對物件的初始建構、儲存和取得

                this.newTemplate.copyId = 0;
                this.newTemplate.id = 0;
                this.newTemplate.isLibrary = true;
                this.newTemplate.studyFacilityScheduleId = this.studyFacilityScheduleId;
                this.studyTermsConditionsService.saveTcTemplate(this.newTemplate)
                    .then(this.studyTermsConditionsService.getTermsConditions)
                    .then(this.setTemplateData);

當這樣設置時,我可以成功保存一個新項目,並獲得它的 id(ng.IPromise 部分)返回給我,並傳入我的 Get 服務調用中。

問題是,當這樣設置時,this.$http.get 回傳的是未定義。據我對其他類似 Stack Overflow 問題的理解,這是因為我在說的時候,呼叫了這個函數卻沒有明確傳入它的參數。

.then(this.studyTermsConditionsService.getTermsConditions)

為了測試這個,我也像這樣設置了保存和獲取

                var data: any;
                data = this.studyTermsConditionsService.saveTcTemplate(this.newTemplate);
                this.studyTermsConditionsService.getTermsConditions(data)
                    .then(this.setTemplateData);

這種方法某種程度上是可行的。$http.Get 被識別並且可以使用,但這個設置的問題是;由於 ng.IPromise 的非同步特性,數據並沒有以承諾的數值傳送到我的 Get 函數中。它被以 $$promise 類型傳送,導致我的 get 函數中的參數是 NaN。

所以我傳遞一個可用的值,也就是 32,但我並沒有明確地傳遞這個值,所以 $http.get 是未定義的。

另一種方法,我明確地傳遞了一個參數,所以 $http.get 可以被識別並使用,但明確呼叫的參數似乎是 $$promise 類型,而不是 number 類型,不幸的是,當我調用我的 Get 函數時,ng.IPromise 尚未解決。

我接下來該怎麼做呢?

答案#1

我猜你對 this 感到困惑。由於你直接將函數引用作為參數傳遞,它就失去了上下文。你應該像下面這樣明確地呼叫它們。

代碼

this.newTemplate.copyId = 0;
this.newTemplate.id = 0;
this.newTemplate.isLibrary = true;
this.newTemplate.studyFacilityScheduleId = this.studyFacilityScheduleId;
this.studyTermsConditionsService.saveTcTemplate((response) => this.newTemplate(response))
    .then((response) => this.studyTermsConditionsService.getTermsConditions(response))
    .then((response) => this.setTemplateData(response));

否則你可以將你的 function 改用 箭頭函數,這將有助於在函數內使用 this 上下文。

saveTcTemplate(item: ITermsConditionsTemplate): ng.IPromise<number> { .. }

應該是

saveTcTemplate = (item: ITermsConditionsTemplate): ng.IPromise<number> => { .. }

和

getTermsConditions(id: number): ng.IPromise<ITermsConditionsTemplate> { .. }

應該是

getTermsConditions = (id: number): ng.IPromise<ITermsConditionsTemplate> => { .. }