欢迎各位兄弟 发布技术文章
这里的技术是共享的
Ask QuestionAsked Active 9 months agoViewed 3k times1
I am following a tutorial on building a MEAN stack authentication app, and I have a problem with my registerUser function that's in my auth.server.ts file.
The instructor is using angular 2, which has caused me problems elsewhere, but I was able to find updated solutions to them. This error has caused me problems with a few other courses and I'm not sure how to fix it.
Here is my code:
registerUser(user) {
let headers = new HttpHeaders();
headers.append('Content-Type', 'application/json');
return this.http.post('http://localhost:5000/users/register', user, { headers: headers }).pipe(map(res => res.json()));
}
Here is the complete auth.service.ts file if you need it:
angular mean-stackshareimprove this questionasked Dec 8 '18 at 8:46
Brian30
Here's the official, correct documentation of HttpClient. Use that as your reference rather than random snippets of code you found on the internet: angular.io/guide/http, angular.io/api/common/http – JB Nizet Dec 8 '18 at 8:52
1what is your angular version? what is the error message? please be more specific – Derviş Kayımbaşıoğlu Dec 8 '18 at 8:59
For Angular 7, it is adviced to use HttpClient rather then Http. You dont need to use .json() to map result in HttpClient. Below you can find example code for this:
对于angular 7,建议使用httpclient,而不是http。您不需要使用.json()在httpclient中映射结果。下面是示例代码:
(在Angular 6中,您不需要将数据映射到json中,因为默认情况下angular 6提供json。)
import { HttpClient } from '@angular/common/http';
registerUser(user) {
let headers = new HttpHeaders();
headers.append('Content-Type', 'application/json');
return this.http.post('http://localhost:5000/users/register', user, { headers: headers });
}
shareimprove this answeranswered Dec 8 '18 at 9:49Derviş Kayımbaşıoğlu17k
Thanks for the help! – Brian Dec 10 '18 at 22:39
If you are using HttpClient
not the Http
then you don't need to use pipe or need to map it to json. You can simply return the response from the API call.
registerUser(user) {
let headers = new HttpHeaders();
headers.append('Content-Type', 'application/json');
return this.http.post('http://localhost:5000/users/register', user, { headers: headers });
}
shareimprove this answeranswered Dec 8 '18 at 8:51Sunil Singh7,290
Thank you for explaining this Sunil – Brian Dec 10 '18 at 22:40