从rxjs / Subject返回数组的Observable(Observable.from与Observable.of)

时间:2017-08-28 23:00:02

标签: angular observable rxjs5

我正在使用WebSockets与后端WebApi进行通信。一切都很好,除了我无法从我的服务中返回我的自定义对象。

我使用的是Angular 4.3.4和rxjs 5.4.3。

//ngInit from my component
ngOnInit() {
    this.modelsSubscription = this.mainService.getModels().subscribe(models => {
      this.models = models;
    });

//here's code from my service
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import { Subject } from 'rxjs/Subject';
import { environment } from '../../environments/environment';

import { WebsocketService } from './websocket.service';
import { MyModel} from '../models/my-Model';
import { ApplicationError } from '../globals/application-error';


@Injectable()
export class MainService {
  messages$: Observable<MyModel[]>;

  private messages: Subject<MyModel[]>;
  private webApiUrl: string;
  private wsApiUrl: string;

  constructor(private http: HttpClient, private wsService: WebsocketService) {
    this.webApiUrl = environment.webApiUrl + '/api/mainscreen/';
    this.wsApiUrl = this.webApiUrl.replace('http:', 'ws:');
  }

  disconnect() {
    this.wsService.disconnect();
  }

  getModels() {
    this.messages = <Subject<MyModel[]>>this.wsService
      .connect(`${this.wsApiUrl}GetModels`)
      .map((response: MessageEvent): Observable<MyModel[]> => {
        const data = JSON.parse(response.data);
        const myModels = MyModel.fromArray(data);
        // return Observable.from(myModels) // <-- throws error Type 'Observable<MyModel>' is not assignable to type 'Observable<MyModel[]>'
         // return myModels; // <-- throws error myModels[] is not assignable to Observable<myModels[]>
        return new Observable<MyModels[]>(observer => {
          observer.next(myModels); // <-- never gets called
          observer.complete();
        });
      })
      .catch((error: any) =>
        Observable.throw(new ApplicationError(error))
      );

    this.messages$ = this.messages.asObservable();
    return this.messages$;
  }    
}

如何从服务中返回Observable?

1 个答案:

答案 0 :(得分:1)

如果你提供一个吸油烟机会更容易。到目前为止,我认为您混淆了Observable.fromObservable.of

<强> Observable.from

此运算符迭代数组元素并将其推送到Observable。这就是您遇到类型兼容性问题的原因: http://reactivex.io/documentation/operators/from.html

<强> Observable.of

此运算符从传递给它的params创建Observable: http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#static-method-of

<强>综述。你应该改变:

return Observable.from(myModels)

为:

return Observable.of(myModels)

示例:

var myModels = ["a", "b", "c", "d"]
Observable.from(myModels).subscribe(value => console.log("value is: " + value));
Observable.of(myModels).subscribe(value => console.log("value is: " + value));

输出将是:

value is: a
value is: b
value is: c
value is: d
value is: [a, b, c, d]