如何在方法实现和调用中对 `http.post.subscribe(…)` 进行操作。

huangapple go评论50阅读模式
英文:

How to act on a http.post.subscribe(...) inside method implementation and calling

问题

我很难理解它们的异步/等待行为。我明白我不能像在dotnet中那样简单地等待调用。我有以下的简单方法,尝试在一些REST API上登录:

  login(email: string, password: string) {

    let httpOptions: Object = {

      headers: new HttpHeaders({
        'Content-Type': 'application/json'
      }),
      responseType: 'text'
    };

    const user: User = { UserName: email, Password: password };
    return this.http.post<User>(`${this.projectsUrl}/login`, user, httpOptions).subscribe(
      (response: any) => {
        localStorage.setItem('id_token', response);
      }
    );
  }

我从我的LoginComponent中调用login方法:

  login() {
    if (this.emailFormControl.value != "" && this.passwordFormControl.value != "") {
      this.authService.login(this.emailFormControl.value!, this.passwordFormControl.value!);
      // 我想获取登录方法的结果,而不是一些订阅
    }
  }

我找到了各种过时解决方案的示例,如.toPromise.map.do。我弄不明白。

英文:

I am having a hard time understanding their async/await behavior. I understand that I can't simply await calls as I am used to in dotnet. I have the following simple method which tries to log in on some rest API:

  login(email:string, password:string ){

    let httpOptions:Object = {

      headers: new HttpHeaders({
        &#39;Content-Type&#39;: &#39;application/json&#39;
      }),
      responseType: &#39;text&#39;
    };

    const user: User = { UserName: email, Password: password };
    return this.http.post&lt;User&gt;(`${this.projectsUrl}/login`, user, httpOptions).subscribe(
      (response : any) =&gt; {
        localStorage.setItem(&#39;id_token&#39;, response);
      }
    );
  }

I am calling the login method from my LoginComponent

  login() {
    if (this.emailFormControl.value != &quot;&quot; &amp;&amp; this.passwordFormControl.value != &quot;&quot;) {
      this.authService.login(this.emailFormControl.value!, this.passwordFormControl.value!);
      // I want to get the result of the login method, NOT some subscription
    }
  }

I am finding all kinds of examples of deprecated solutions like .toPromise, .map, and .do. I can't figure it out.

答案1

得分: 0

I figured out a way after the suggestion of jonrsharpe.

  async login(email: string, password: string) {

    let httpOptions: Object = {

      headers: new HttpHeaders({
        'Content-Type': 'application/json'
      }),
      responseType: 'text'
    };

    const user: User = { UserName: email, Password: password };
    const result$ = this.http.post<any>(`${this.projectsUrl}/login`, user, httpOptions);
    let token = await lastValueFrom(result$);

    if (token !== "") {
      localStorage.setItem('id_token', token);
      this.messageService.add(`auth serv: token ${token}`);
      this.loggedIn = true;
    }

    return this.loggedIn;
  }

If there is a better way of doing this I'd be happy to hear that.

英文:

I figured out a way after the suggestion of jonrsharpe.

  async login(email:string, password:string ){

    let httpOptions:Object = {

      headers: new HttpHeaders({
        &#39;Content-Type&#39;: &#39;application/json&#39;
      }),
      responseType: &#39;text&#39;
    };

    const user: User = { UserName: email, Password: password };
    const result$ = this.http.post&lt;any&gt;(`${this.projectsUrl}/login`, user, httpOptions);
    let token = await lastValueFrom(result$);

    if (token != &quot;&quot;) {
      localStorage.setItem(&#39;id_token&#39;, token);
      this.messageService.add(`auth serv: token ${token}`);
      this.loggedIn = true;
    }

    return this.loggedIn;
  }

if there is a better way of doing this I'd be happy to hear that.

答案2

得分: 0

You return the subscription. Return the observable:

...
return this.http.post<User>(`${this.projectsUrl}/login`, user, httpOptions).pipe(
  tap((response) => localStorage.setItem('id_token', response)),
);
...

And subscribe in the component:

...
this.authService.login(...).subscribe(console.log);
...
英文:

You return the subscription. Return the observable:

...
return this.http.post&lt;User&gt;(`${this.projectsUrl}/login`, user, httpOptions).pipe(
  tap((response) =&gt; localStorage.setItem(&#39;id_token&#39;, response)),
);
...

And subscribe in the component:

...
this.authService.login(...).subscribe(console.log);
...

huangapple
  • 本文由 发表于 2023年4月4日 03:59:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/75923339.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定