2017-09-06 37 views
2

我想張貼在WordPress的通過我的API應用程序離子的註釋,但它說,錯誤401(非法),這意味着WordPress的API認爲我沒有登錄..beforesend的打字稿相當於在Javascript

我的代碼:

postComment(params?: any) { 
let nonce = localStorage.getItem('nonce'); 
let seq = this.api.post('wp', 'comments', "post="+ params.post+ "&author_name="+params.author_name+"&author="+params.author+"&[email protected]&content=something").share(); 
    seq 
    .map(res => res.json()) 
    .subscribe(res => { 
    }, err => { 
     console.error('ERROR', err); 
    }); 
    return seq; 

}

在我的研究是說我需要發送的隨機數,我可以做這樣的:

.ajax({ 
    url: wpApiSettings.root + 'wp/v2/posts/1', 
    method: 'POST', 
    beforeSend: function (xhr) { 
    xhr.setRequestHeader('X-WP-Nonce', wpApiSettings.nonce); 
    }, 
    data:{ 
     'title' : 'Hello Moon' 
    } 
    }).done(function (response) { 
}); 

如何在打字稿中做到這一點?如何在打字稿中放入beforeSend函數xhr.setRequestHeader?

+0

只要是明確的 - 這是一個角度與jQuery的區別,而不是一個打字稿與JavaScript的差異, –

回答

0

setRequestHeader方法設置與您的請求一起發送的標頭。在離子/角完成這件事的方式是頭對象添加到requestoptions參數:

let opts: RequestOptionsArgs = {}; 
let headers = new Headers(); 

headers.append('X-WP-Nonce', nonce); 
opts.headers = headers; 

return this.http.post(fullPath, requestBody, opts) 
    .map(this.extractData) 
    .catch(this.handleError); 
+0

試了一下它說:類型'標題'不可分配給類型'標題'/兩個不同類型的名稱存在,但它們是不相關的。 'Headers'類型中缺少屬性'keys'。 – Domy

+0

然後你有一個類型不匹配,檢查你的進口。頭文件類應該從'@ angular/http'中導入。如果你無法弄清楚,那麼將代碼添加到問題中,我可以看一看 – hagner