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)
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()功能将在您的订户上调用.
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调用而不是静态数据.
截至 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)
| 归档时间: |
|
| 查看次数: |
98863 次 |
| 最近记录: |