I am calling a JSON file using rx/js Observable.
Service
constructor(private http: Http){
}
getUserById():Observable<User[]> {
let url = this.mockData;
let header = new Headers({'Content-Type': 'application/json'});
return this.http.get(url)
.map((res:Response) =><User[]>res.json())
.do(data => console.log("User Data: "+JSON.stringify(data)))
.catch((error:any) => Observable.throw(error) || "Mock Data Error get by role")
};
component:
@Input() users: User[] = [];
userTemp: User[] = [];
getUserById(userId){
this._searchService.getUserById()
.filter(users => {
for(let user of users){
if(user.userName === userId){
this.userTemp.push(user);
}}});
return this.userTemp;
}
under users => {
says when I hover over it (Users: Users[]) => void is not assignable) => boolean.
I know there is a small detail I am missing but I am not sure where it is. Any advice would be greatly appreciated.
------------------------------update 1-------------------------- Trying this now but and it compiles but doesn't work.
this._searchService.getUserById()
._do(users => {
for(let user of this.users){
if(user.id == userId){
this.userTemp.push(user);
}
}
});
---------------------Update 2-------------------------- I got some advice from the posts below and now I am trying to do it like this, but it is rendering nothing and giving no errors.
In component:
@Input() users: IUser[] = [];
Method being called in component:
case 'role':
this.users = this.getUserByRole(this.role);
console.log(this.role);
break;
method in component:
getUserByRole(role){
this._searchService.getUsers()
.subscribe(users => {
for(let user of users) {
if(user.role == role){
this.users.push(user);
}}});
return this.users;
}
Service method:
getUsers(): Observable<IUser[]> {
let users = this.http
.get(this.url)
.map(res => res.json());
return users;
}
In the console it will print whatever I put in the input box and I confirmed the url
for the http call is valid.
I am trying to do it like this so all I need to do is change the http url to have headers and a real url later without have to change to much.
--------------Update 3----------------------
In the HTML I have:
<td>{{data.role | async}}</td>
method in component:
getUserByRole(role){
return this._searchService.getUsers()
.map(data => {
return data.filter((x:any) => x.role == role)
});
}
Field:
@Input() users: Observable<IUser[]>;
Calling the method:
case 'role':
console.log(this.getUserByRole(this.role));
this.users = this.getUserByRole(this.role);
console.log(this.users);
break;
error:
Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
In my searchService I am now looking at doing it this way but still not working:
findUserByRole(user: IUser) {
return this.http.get(this.url)
.map(res => res.json())
.subscribe(
data => {
}
);
}