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

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

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

问题

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

  1. login(email: string, password: string) {
  2. let httpOptions: Object = {
  3. headers: new HttpHeaders({
  4. 'Content-Type': 'application/json'
  5. }),
  6. responseType: 'text'
  7. };
  8. const user: User = { UserName: email, Password: password };
  9. return this.http.post<User>(`${this.projectsUrl}/login`, user, httpOptions).subscribe(
  10. (response: any) => {
  11. localStorage.setItem('id_token', response);
  12. }
  13. );
  14. }

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

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

我找到了各种过时解决方案的示例,如.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:

  1. login(email:string, password:string ){
  2. let httpOptions:Object = {
  3. headers: new HttpHeaders({
  4. &#39;Content-Type&#39;: &#39;application/json&#39;
  5. }),
  6. responseType: &#39;text&#39;
  7. };
  8. const user: User = { UserName: email, Password: password };
  9. return this.http.post&lt;User&gt;(`${this.projectsUrl}/login`, user, httpOptions).subscribe(
  10. (response : any) =&gt; {
  11. localStorage.setItem(&#39;id_token&#39;, response);
  12. }
  13. );
  14. }

I am calling the login method from my LoginComponent

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

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.

  1. async login(email: string, password: string) {
  2. let httpOptions: Object = {
  3. headers: new HttpHeaders({
  4. 'Content-Type': 'application/json'
  5. }),
  6. responseType: 'text'
  7. };
  8. const user: User = { UserName: email, Password: password };
  9. const result$ = this.http.post<any>(`${this.projectsUrl}/login`, user, httpOptions);
  10. let token = await lastValueFrom(result$);
  11. if (token !== "") {
  12. localStorage.setItem('id_token', token);
  13. this.messageService.add(`auth serv: token ${token}`);
  14. this.loggedIn = true;
  15. }
  16. return this.loggedIn;
  17. }

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.

  1. async login(email:string, password:string ){
  2. let httpOptions:Object = {
  3. headers: new HttpHeaders({
  4. &#39;Content-Type&#39;: &#39;application/json&#39;
  5. }),
  6. responseType: &#39;text&#39;
  7. };
  8. const user: User = { UserName: email, Password: password };
  9. const result$ = this.http.post&lt;any&gt;(`${this.projectsUrl}/login`, user, httpOptions);
  10. let token = await lastValueFrom(result$);
  11. if (token != &quot;&quot;) {
  12. localStorage.setItem(&#39;id_token&#39;, token);
  13. this.messageService.add(`auth serv: token ${token}`);
  14. this.loggedIn = true;
  15. }
  16. return this.loggedIn;
  17. }

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:

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

And subscribe in the component:

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

You return the subscription. Return the observable:

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

And subscribe in the component:

  1. ...
  2. this.authService.login(...).subscribe(console.log);
  3. ...

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:

确定