2017-09-06 67 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