如何在Angular中进行HTTP发布请求后保存JSON数据

时间:2018-08-02 06:15:20

标签: angular typescript http local-storage

您好,这是我的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的初学者

1 个答案:

答案 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的信息。