I encountered a challenge in my angular application while trying to create an observable array using rxjs.
Here is the code snippet:
import { Injectable } from "@angular/core";
import { Observable } from "rxjs/Rx";
import { User } from "../model/user";
@Injectable()
export class UserService {
public GetList(): Observable<User[]> {
return Observable.of(this.GetDummyData());
}
private GetDummyData(): Array<User> {
var users: Array<User> = new Array<User>();
users.push(new User(1, "user one", 1, 1000001, true));
users.push(new User(2, "user two", 2, 1000002, false));
users.push(new User(3, "user three", 3, 1000003, true));
return users;
}
}
The above code results in the following error:
ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'of' of undefined
It seems like the static method is not available. I tried a couple of approaches to resolve this issue:
- Using the constructor and creating an instance of an observable (Not successful,
)error Uncaught (in promise): TypeError: Rx_1.Observable is not a constructor
- Changing the import statements as shown below (Error persists)
import { Observable } from "rxjs/Observable";
import "rxjs/Observable/of";
Do you have any suggestions on how to fix this issue?
Here are the versions of libraries used:
"@angular/common": "4.0.1",
"@angular/compiler": "4.0.1",
"@angular/core": "4.0.1",
"@angular/forms": "4.0.1",
"@angular/http": "4.0.1",
"@angular/platform-browser": "4.0.1",
"@angular/platform-browser-dynamic": "4.0.1",
"@angular/animations": "4.0.1",
"@angular/router": "4.0.1",
"core-js": "2.4.1",
"reflect-metadata": "0.1.10",
"rxjs": "5.4.1",
"systemjs": "0.20.11",
"zone.js": "0.8.5",
EDIT I might be facing a more complex issue here. Upon reviewing the documentation and realizing that there was no explicit mention of ES5, which is my target for compilation, I suspect that there may be some compatibility issues with my modules.
Below is a glimpse of my setup:
tsconfig.json
{
"compilerOptions": {
"target": "es5",
"module": "system",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": false,
"noImplicitAny": false,
"lib": ["es5", "es2015", "dom" ]
}
}
None of the library versions mentioned work for me, suggesting a potential incompatibility with my modules.
However, the following approach seems to work but is not optimal due to excessive loading:
import { Observable } from "rxjs/Rx";
import Rx from 'rxjs/Rx';
import 'rxjs/add/observable/of';
public GetList(): Observable<User[]> {
return Rx.Observable.of(this.GetDummyData());
}
Based on my understanding, this signifies that Rx.Observable is defined while Observable (as previously utilized) is not accessible.