Stav Alfi Stav Alfi - 4 months ago 18
TypeScript Question

how to get data using Http.get from my project?

I got a ts file that contain some users:

quickstart-muster/app/mock/user.mock.ts:

import {User} from "../user";

export const USERS:User[]=[
new User(....);
];


A serice - quickstart-muster/app/services/user.service.ts:

import { Injectable } from '@angular/core';
import {Observable} from "rxjs/Observable"
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/fromPromise';
import 'rxjs/add/operator/toPromise';
import {Http} from "@angular/http";
import {User} from "../user";

@Injectable()
export class UserService {

constructor(private http:Http){}

public loadUsers():Observable<User[]>{
return this.http.get('../mock/user.mock.ts')
.map(res=>res.json());
}
}


I know thats not gonna work and its not, i get 404 error that say he can't find .../mock/user.mock.ts.

How do I make it work?

Answer

You could load a JSON file instead like it would come from the API:

/data.json

[
    {
        "id": 1234,
        "name": "...",
        ...
    },
    ...
]

and then you can load it like this:

public loadUsers(): Observable<User[]>{
  return this.http.get('data.json')
    .map(res => res.json());
}

You could also create an Observable from scratch like this:

public loadUsers(): Observable<User[]> {
    return Observable.create((observer) => {
        observer.onNext(USERS);
        observer.onCompleted();
    });
}
Comments