請問有關 Subscribe 的問題:
如下面所PO的程式來看:
- 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 -------------------