0

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?

1
  • Try two dots instead of three: "../mock/user.mock.ts". Please add a tag for the programming language. Commented Aug 2, 2016 at 12:56

2 Answers 2

1

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();
    });
}
Sign up to request clarification or add additional context in comments.

8 Comments

Thansk for the answer! Is there anyway I could use "new User(params...)" inside a json file? If not, is that the only way to acomplish what I'm trying to do?
I added another possibility! :)
You can put whatever value you want in the .onNext call. Potentially an array with users!
Okay I changed to : http.get('.../mock/user.mock.json') but I still get 404 not found error. Any idea why?
Haha, ok ... then just put that JSON file besides your index.html and the browser will find it at 'data.json' ... Your start point of 'relativity' is the folder with the index.html. If you have a folder called app and then mock, then the right path might be 'app/mock/data.json'.
|
0

Use Promise.resolve instead of http get

public loadUsers():Observable<User[]>{
    return Promise.resolve([ new User(....);]);
  }

1 Comment

I want to use http.get and later I will only change the adress to a real server.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.