我有一个服务,其中有这个方法:
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时会发生这种情况),以便在两种情况下都有无缝处理。
import { of } from 'rxjs';
并使用of
,而不是Observable.of
。 - vip.map()
函数,因此需要使用.pipe(map((res:any) => res.json()))
。参见这里:https://dev59.com/51wX5IYBdhLWcg3wjgCf#35220045。 - Michail Michailidis