如何等到订阅完成 | Angular 9

How to wait until subscribe finishes | Angular 9

我的任务是在 contest.service.ts 中创建一个方法,该方法将从服务器获取数据(竞赛),对其进行必要的操作,然后 return结果。

contest.service.ts:

    getContests() {
        let id = IDs.contests.getAll;
        let body = { 
            ...
        };

        let result;

        this.wsservice.send(id, body);

        this.wsservice.on<any>(IDs.contests.getAll)
            .subscribe((msg) => {
                console.log('msg', msg);
                if (!msg['code']) {
                    result = msg;
                    console.log('contests msg', result);
                    this.contests = result.map(contest => {
                        return new Contest({
                            id: contest.id,
                            name: contest.name || "Нет названия",
                            description: contest.description,
                            contestTasks: contest.tasks || []
                        });
                    });
                }
                else {
                    result = "Error";
                }
            });

        return result;
    }

我需要等到订阅 this.wsservice.on(IDs.contests.getAll) 完成,然后 return 它的结果。 来自websocket.service.ts的方法:

    public send(eventId: any, data: any = {}): void {
        console.log('SEND');
        let that = this;
        if (eventId && this.isConnected && this.websocket$) {
            data['id'] = eventId;
            this.websocket$.next(data);
        } else {
            setTimeout(function() {
                that.send(eventId, data);
            }, 500);
            console.log('Still connecting, resending messsage...');
        }
    }

    public on<T>(eventId: any): Observable<T> {
        console.log(eventId);
        if (eventId) {
            return this.wsMessages$.pipe(
                filter((message: IWsMessage<T>) => message.id === eventId),
                map((message: IWsMessage<T>) => message.result ? message.result : message.error)
            );
        }
    }

改进我的评论。

你应该 return 一个可观察的。您可以使用

getContests() {
   ....
   return this.wsservice.on<any>(IDs.contests.getAll).pipe(
    //we don't want the response else
    switchMap(msg)=>{
      ..do something with the msg..
      //create an object
      const contest= new Contest({
                 ...});
       //we need return an observable, we use rxjs operator 'of'
       return of(contest)
   }
   )

或使用地图

getContests() {
   ....
   return this.wsservice.on<any>(IDs.contests.getAll).pipe(
    //we are going to transform the response
    map(msg)=>{
      ..do something with the msg..
      //create an object
      const contest= new Contest({
                 ...});
       return contest; //<--see that return simple the object
   }
   )

看到 return 一个 observable,所以在你的组件中订阅

this.service.getContests().subscribe(res=>{
   //here you has the object contest
   console.log(res)
})