How to get value in Response header Angular2

2020-02-09 01:01发布

i want to get session token in response header(Set-Cookie).how can i access values in Response header ?

var headers = new Headers();
            headers.append('Content-Type', 'application/json');
            console.log('url',this.loginUrl)
            this.http.post(this.loginUrl,
                JSON.stringify({ "username": value.username, "password": value.password }),
                { headers: headers })
                .map((res: Response) => 
                    res.json())
                .subscribe((res) => {
                    console.log("res", res);
                    this.loading.hide();
                    if (res.message_code == "SUCCESS") {
                        this.nav.setRoot(HomePage, {
                            username: value.username,
                        });
                    } else {
                        let alert =  Alert.create({
                            title: "Sign In Error !",
                            subTitle: 'Please Check Username or Password.',
                            buttons: ['Ok']
                        });
                        this.nav.present(alert);
                    }
                }, err => {
                    this.loading.hide();
                    console.log('error', err);

                }); 

this is my header response

enter image description here

标签: http angular
8条回答
爷、活的狠高调
2楼-- · 2020-02-09 01:53

.map((res: Response) => { localStorage.setItem('setCookie', res.headers._headers.get("Set-Cookie")[0]); res.json() })

or you can take reference from https://angular.io/docs/ts/latest/api/http/index/Headers-class.html

查看更多
放我归山
3楼-- · 2020-02-09 01:54

Another solution with Angular 4.2.+;

Service

getProfile(data) {
   return this.httpClient
      .request(new HttpRequest("POST", this.url, {}));
}

Component

this.userService.getProfile().subscribe(
  (response: any) => {
    if (response.type === HttpEventType.Response) {
      // response.headers is here
    }
  },
  (error: HttpErrorResponse) => {
    this.showMessage("error", "An error occurred");
  }
);
查看更多
登录 后发表回答