如何将从http.post返回的简单字符串值设置为Angular5中的变量

时间:2018-02-20 08:16:18

标签: angular resteasy angular5

我想通过http.post从我的Restful webservice获取一个令牌。 webservice采用用户名和密码,如果参数与数据库中的任何用户匹配,则会创建一个令牌并将其作为字符串返回。我可以发送帖子并将值作为JSON,但我想把它作为字符串。我想用它作为变量。我希望有关于http和休息服务通信的清晰知识,如果有人可以建议一个对我来说非常好的来源。提前谢谢......

我可以接受它,但我想把它作为一个变量或变量在类中 界面:

export interface Token {
    token: string
}

auth.service.ts:

login (username: string, password: string): Observable<Token[]> {
      this.params = '?username=' + username + '&password=' + password;
      return this.http.post<Token[]>(this.loginURL + this.params, null, httpOptions).do(data => console.log(data));
  }

login.component.ts:

this.authService.login(this.username, this.password).subscribe(data => this.authService.token = data[0]);

更新和工作

我用@ SrAxi的帮助解决了这个问题。最终正确的代码;

我的login.component.ts:

this.authService.login(this.username, this.password).subscribe(
            (data: string) => this.authService.token.token = data,
            (error: any) => console.error(error.message, error.details),() => console.log(this.authService.token.token)
        );

我的auth.service.ts:

 login(username: string, password: string): Observable<string> {
        this.params = '?username=' + username + '&password=' + password;
        return this.http.post(this.loginURL + this.params, null, httpOptions)
            .map((response: Token) => response.token) // we navigate in the repsonse directly and fish out the token and return it
            .catch((error: any) => Observable.throw(error));
    }

和我的对象类:

export class Token {
    private _token: string;


    get token(): string {
        return this._token;
    }

    set token(value: string) {
        this._token = value;
    }
}

2 个答案:

答案 0 :(得分:0)

您没有映射来自Http呼叫的响应。

login(username: string, password: string): Observable<string> {
    this.params = '?username=' + username + '&password=' + password;
    return this.http.post(this.loginURL + this.params, null, httpOptions)
      .map((response: any) => response.json().token) // we navigate in the repsonse directly and fish out the token and return it
      .catch((error: any) => Observable.throw(error));
  }

通过这个重新设计的功能,您将能够映射响应并将其解析为JSON,或者抛出订阅将会捕获的错误。

所以你可以这样称呼它:

this.authService.login(this.username, this.password).subscribe(
      (data: any) => this.authService.token = data[0],
      (error: any) => console.error(error.message, error.details)
    );

答案 1 :(得分:0)

在您的身份验证服务中,请执行以下操作

login (username: string, password: string): Observable<Token> {
  this.params = '?username=' + username + '&password=' + password;
  return this.http.post(this.loginURL + this.params, null, httpOptions).map((res: Token) => res);
  }

然后在您的登录组件

    ...
    token: Token = null;
    this.authService.login(this.username, this.password)
   .subscribe(token => this.token = token);
    ...