我有一个具有此方法的服务:
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());
}
}
}
在组件的构造函数中,我像这样订阅:
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)
);
}
}
如果一个对象来自服务器,但我正在尝试创建一个可观察对象,它将与给定的
subscribe()
调用静态字符串一起使用(当 testModelService.fetchModel()
没有收到 uuid 时会发生这种情况),因此可以进行无缝处理在这两种情况下。
也许你可以尝试使用 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());
}
}
截至 2018 年 7 月和
RxJS 6
的发布,从值获取 Observable 的新方法是导入 of
运算符,如下所示:
import { of } from 'rxjs';
然后根据值创建可观察值,如下所示:
of(someValue);
请注意,您过去必须像当前接受的答案一样执行
Observable.of(someValue)
。有一篇关于 RxJS 6 其他更改的好文章这里。
自 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());
}
}
您的订阅者将调用
.next()
函数。
这就是为静态数据创建简单可观察对象的方法。
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
});
希望这个答案对您有所帮助。我们可以使用 HTTP 调用来代替静态数据。
截至 2021 年 5 月,从值获取 Observable 的新方法是:
导入:
import "rxjs/add/observable/of"
import { Observable } from "rxjs/Observable"
并使用它,就像这样::
Observable.of(your_value)
这样你就可以从数据创建Observable,在我的例子中我需要维护购物车:
服务.ts
export class OrderService {
cartItems: BehaviorSubject<Array<any>> = new BehaviorSubject([]);
cartItems$ = this.cartItems.asObservable();
// I need to maintain cart, so add items in cart
addCartData(data) {
const currentValue = this.cartItems.value; // get current items in cart
const updatedValue = [...currentValue, data]; // push new item in cart
if(updatedValue.length) {
this.cartItems.next(updatedValue); // notify to all subscribers
}
}
}
组件.ts
export class CartViewComponent implements OnInit {
cartProductList: any = [];
constructor(
private order: OrderService
) { }
ngOnInit() {
this.order.cartItems$.subscribe(items => {
this.cartProductList = items;
});
}
}