如何从Angular中类似于http的静态数据创建一个Observable?

Mic*_*dis 97 promise observable rxjs typescript angular

我有一个具有此方法的服务:

export class TestModelService {

    public testModel: TestModel;

    constructor( @Inject(Http) public http: Http) {
    }

    public fetchModel(uuid: string = undefined): Observable<string> {
        if(!uuid) {
            //return Observable of JSON.stringify(new TestModel());
        }
        else {
            return this.http.get("http://localhost:8080/myapp/api/model/" + uuid)
                .map(res => res.text());
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在组件的构造函数中,我订阅如下:

export class MyComponent {
   testModel: TestModel;
   testModelService: TestModelService;

   constructor(@Inject(TestModelService) testModelService) {
      this.testModelService = testModelService;

      testService.fetchModel("29f4fddc-155a-4f26-9db6-5a431ecd5d44").subscribe(
          data => { this.testModel = FactModel.fromJson(JSON.parse(data)); },
          err => console.log(err)
      );
   }
}
Run Code Online (Sandbox Code Playgroud)

如果一个对象来自服务器,但是我试图创建一个可以使用给定subscribe()的静态字符串调用的observable (当testModelService.fetchModel()没有收到uuid 时会发生这种情况),这样就可以了.所以在这两种情况下都有无缝处理.

Thi*_*ier 129

也许您可以尝试使用该类的of方法Observable:

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';

public fetchModel(uuid: string = undefined): Observable<string> {
  if(!uuid) {
    return Observable.of(new TestModel()).map(o => JSON.stringify(o));
  }
  else {
    return this.http.get("http://localhost:8080/myapp/api/model/" + uuid)
            .map(res => res.text());
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 如果您使用的是版本6,那么您必须从'rxjs'中导入{of};`并使用`of`而不是`Observable.of`. (29认同)
  • 这太棒了!有效!我正在尝试很多事情,例如Observable.from()等。Observable的API文档目前还不是最干净/最用户友好的!谢谢 :) (2认同)
  • 对于Angular v7.xx,获取结果上没有`.map()`,因此您需要执行`.pipe(map((res:any)=&gt; res.json()))`。看到这里:/sf/answers/2465403181/ (2认同)

VSO*_*VSO 46

从2018年7月开始发布RxJS 6,从值中获取Observable的新方法是导入of运算符,如下所示:

import { of } from 'rxjs';

然后从值中创建observable,如下所示:

of(someValue);

请注意,您以前Observable.of(someValue)在当前接受的答案中必须这样做.还有另RxJS一个很好的第6点的变化在这里.


Nie*_*Wet 17

自Angular 2.0.0以来,事情似乎发生了变化

import { Observable } from 'rxjs/Observable';
import { Subscriber } from 'rxjs/Subscriber';
// ...
public fetchModel(uuid: string = undefined): Observable<string> {
  if(!uuid) {
    return new Observable<TestModel>((subscriber: Subscriber<TestModel>) => subscriber.next(new TestModel())).map(o => JSON.stringify(o));
  }
  else {
    return this.http.get("http://localhost:8080/myapp/api/model/" + uuid)
            .map(res => res.text());
  }
}
Run Code Online (Sandbox Code Playgroud)

.next()功能将在您的订户上调用.

  • @MichailMichailidis,经过一个月的回顾,在我看来两者同样有效,主要区别在于Thierry的解决方案要求你导入rxjs的`of`函数,比如`import'rxjs/add/observable/of'` (7认同)
  • 我已经迁移到Angular 2.1.2 ..旧的方式似乎仍然受到支持..请你详细说明为什么这是一个更好的解决方案或者是惯例?然后我将在我的代码中的所有位置更改它,我将重新接受..谢谢 (2认同)

Bal*_*wal 10

这是为静态数据创建简单observable的方法.

let observable = Observable.create(observer => {
  setTimeout(() => {
    let users = [
      {username:"balwant.padwal",city:"pune"},
      {username:"test",city:"mumbai"}]

    observer.next(users); // This method same as resolve() method from Angular 1
    console.log("am done");
    observer.complete();//to show we are done with our processing
    // observer.error(new Error("error message"));
  }, 2000);

})

to subscribe to it is very easy

observable.subscribe((data)=>{
  console.log(data); // users array display
});
Run Code Online (Sandbox Code Playgroud)

我希望这个答案很有帮助.我们可以使用HTTP调用而不是静态数据.


dan*_*ilo 6

截至 2021 年 5 月,从值获取 Observable 的新方法是:

输入:

import "rxjs/add/observable/of"
import { Observable } from "rxjs/Observable"
Run Code Online (Sandbox Code Playgroud)

并使用它,就像这样::

Observable.of(your_value)
Run Code Online (Sandbox Code Playgroud)