问题描述
我想请你帮忙。我省略code,我认为并不重要。让我们想象一下TS文件,其中包含服务电话:
I'd like to ask you for help. I omitted code that I assume is not important. Let's imagine TS file that contains service calls:
//文件:someService.ts
// file: someService.ts
@Injectable()
export class SomeService {
method1(){
var observable = this.http.get(someUrl)
.map((res: Response) =><MyClass[]>res.json());
return observable;
}
method2(){
// Similar to method1
}
}
//文件:someComponent.ts
// file: someComponent.ts
请注意,this.method1observable和method2observable已正确父(根)组件分配和它们的类型是可观的。
Please note, that this.method1observable and method2observable are properly assigned from parent (root) component and their type is Observable.
import {Observable} from 'rxjs/Observable';
export class SomeClass {
public m1: Observable<MyClass[]>;
public m2: Observable<AnotherClass[]>
ngOnInit() {
Observable.forkJoin(this.m1,this.m2) //<- ERROR HERE
.subscribe(data => {
this.myFunction(data[0], data[1]);
requestAnimationFrame(this.renderLoop);
});
}
}
我得到的未捕获的ReferenceError:观测没有定义。
难道你不知道我究竟做错了什么?我看到一些例子,Observable.forkJoin称为服务中。但是,如果我想要把它称为一个组件内?
I get "Uncaught ReferenceError: Observable is not defined".Don't you know what am I doing wrong? I saw some examples where Observable.forkJoin is called inside a service. But what if I want to call it inside a component?
推荐答案
您可以尝试导入这种方式:
You could try to import this way:
import {Observable} from 'rxjs/Rx';
而不是:
import {Observable} from 'rxjs/Observable';
您也应该使用数组提供您观测到forkJoin方法:
You should also use an array to provide your observables to the forkJoin method:
ngOnInit() {
Observable.forkJoin([this.m1,this.m2])
.subscribe(data => {
this.myFunction(data[0], data[1]);
requestAnimationFrame(this.renderLoop);
});
}
和别忘了@Component指定输入:
And do not forget to specify inputs in @Component:
@Component({
inputs: ['m1', 'm2']
})
这篇关于观测变量的Angular2 Observable.forkJoin - 的ReferenceError:观测没有定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!