請問有關 Subscribe 非同步的問題

請問有關 Subscribe 的問題:
如下面所PO的程式來看:

  1. HomeComponent 執行 doTest() 後,在 memberService.getMember() 還沒回傳結果時,其後續的 console.log ('doTest(): …) 就已經執行完畢了。

在下的問題是:如何讓 memberService .getMember(…) 執行結果回傳後,才繼續執行 doTest()中的後續的 console.log('doTest(): …) ?

謝謝。

程式碼:

==HomeComponent===============

import {AfterViewInit, Component, OnInit, ViewChild} from '@angular/core';
import { HttpErrorResponse} from '@angular/common/http';
import {MemberService} from '../service/member.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit, AfterViewInit {

  constructor(
    private memberService: MemberService
  ) {
    
  }
  ngOnInit() {
  }
  ngAfterViewInit(): void {
    
  }

  doTest() {
    const result = this.memberService.getMember('user123@mail.com');
    console.log('doTest(): call done');
    console.log('doTest(): result is :' + result);
  }
}

=== MemberService ==========================

import { Injectable } from '@angular/core';
import {HttpClient, HttpErrorResponse} from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class MemberService {
  apiUrl = 'http://localhost:8080';
  constructor(private httpClient: HttpClient) { }

  getMember(memberEmail: string) {
    const url = this.apiUrl + '/member/' + memberEmail;
    let finalResult = null;
    this.httpClient.get(url, {}).subscribe(
      (result: any) => {
        finalResult = result;
        console.log('getMember(): result is ' + JSON.stringify(result));
      },
      (httpError: HttpErrorResponse) => {

      },
      () => {
        console.log('getMember(): COMPLETE -------------------');
      }
    );
    console.log('getMember(): before return finalResult ........');
    return finalResult;
  }
}

===== OUTPUT =====================

getMember(): before return finalResult ........ [main.js:961:17](http://localhost:4200/main.js)

doTest(): call done [main.js:395:17](http://localhost:4200/main.js)

doTest(): result is :null [main.js:396:17](http://localhost:4200/main.js)

getMember(): result is {"resultCode":"SUCCESS","data":{"id":1,"mamberActionLogs":[],"isActive":true,"dateCreated":{"dayOfMonth":26,"dayOfWeek" ....} 略過

getMember(): COMPLETE -------------------

doTest() {
console.log(‘doTest(): call done’);
this.memberService.getMember(‘user123@mail.com’).subscribe((result: any) =>{
console.log(‘doTest(): result is :’ + result);
});
}

@stack 謝謝。
這個作法我知道,但我希望能把 subscribe 也包在 getMember() 裡面,這樣 component 才不會顯得太亂太肥。
不知是否還有其他的作法?謝謝

使用 rxjs 的目的就是要讓動作與動作間是可以作結合的,如果把 observable 當 promise 使用,那就有點浪費了

而且使用 async pipe 就不用使用 subscribe, 給個方向思考看看

我觉得Observable最好不要这么使用,你service里面subscribe部分的代码的执行时机在你的component里面根本无法控制,你想要达到的效果完全是promise的用法,那么为什么一定要用Observable呢,要不就用toPromise把你的Observable转化成promise,然后调用await。