您好,这是我的import 'core-js/es6/map';
import 'core-js/es6/set';
代码
http post
成功完成createPost(input:HTMLInputElement){
// input.value='';
let post={content:input.value};
let head = new Headers({ 'Content-Type': 'application/json' });
let requestOptions = new RequestOptions({headers: head});
let body = JSON.stringify(post);
this.http.post(this.url,body,requestOptions)
.subscribe(response => {
post['id']=response.json().id;
this.posts.splice(0,0,post);
});
请求后,我的服务器将响应一个令牌以进行身份验证以发出该请求,该令牌将采用 JSON 格式。现在,有什么方法可以让我实时获取该令牌并在http post
调用之后直接将其存储在本地存储中
我能理解http post
的概念,但所有人都不知道该在哪里根据我的代码的具体实现它们
这个问题可能对您来说很愚蠢,但我只是Angular的初学者
答案 0 :(得分:1)
您可以拥有一个LoginService
来获取令牌并将其保存在localStorage
中。它还可以使用名称为isAuthenticated
的另一种方法来验证客户端是否已通过身份验证。完成请求后
this.http.post(this.url,body,requestOptions)
.subscribe(response => {
post['id']=response.json().id;
this.posts.splice(0,0,post);
// Here you need to store the token in the localStorage
// localStorage.setItem('access_token', yourToken)
});
您需要将令牌存储在localStorage中,然后使用此服务执行与令牌相关的下一步操作。
其他方法可能类似于
getToken() : string {
return localStorage.getItem('access_tojen');
}
isAuthenticated() : boolean {
const token = getToken();
return /* your logic here */.
}
您还可以查看有关Authentication的信息。