6

I'm doing a POC to prove I have communication between the back end and front end in Angular Universal. I've got a JSON file in the back end called heroes.json that I want to retrieve from the front end service ModelService in model.service.ts.

I have this folder structure:

enter image description here

Within model.service.ts (front end) I want to create an http request to get some data in a method called getStuff().

I have this in model.service.ts:

// domain/feature service
@Injectable()
export class ModelService {
  private heroesUrl = "http://localhost:4000/src/backend/heroes.json"; // URL to JSON file
   // This is only one example of one Model depending on your domain
  constructor(public api: ApiService, public cacheService: CacheService, private http: Http) {

  }

  public getStuff(): Observable<any[]> {
        return this.http.get(this.heroesUrl)
                    .map(this.extractData)
                    .catch(this.handleError);
  }

    private extractData(res: Response) {
    let body = res.json();
    return body.data || { };
  }

    private handleError (error: Response | any) {
    // In a real world app, we might use a remote logging infrastructure
    let errMsg: string;
    if (error instanceof Response) {
      const body = error.json() || "";
      const err = body.error || JSON.stringify(body);
      errMsg = `${error.status} - ${error.statusText || ""} ${err}`;
    } else {
      errMsg = error.message ? error.message : error.toString();
    }
    console.error(errMsg);
    return Observable.throw(errMsg);
  }

    // domain/feature service
    @Injectable()
    export class ModelService {
      private heroesUrl = "http://localhost:4000/src/backend/heroes.json"; // URL to JSON file
       // This is only one example of one Model depending on your domain
      constructor(public api: ApiService, public cacheService: CacheService, private http: Http) {

      }

      public getStuff(): Observable<any[]> {
            return this.http.get(this.heroesUrl)
                        .map(this.extractData)
                        .catch(this.handleError);
      }

        private extractData(res: Response) {
        let body = res.json();
        return body.data || { };
      }

        private handleError (error: Response | any) {
        // In a real world app, we might use a remote logging infrastructure
        let errMsg: string;
        if (error instanceof Response) {
          const body = error.json() || "";
          const err = body.error || JSON.stringify(body);
          errMsg = `${error.status} - ${error.statusText || ""} ${err}`;
        } else {
          errMsg = error.message ? error.message : error.toString();
        }
        console.error(errMsg);
        return Observable.throw(errMsg);
      }

From a front end component I am calling the ModelService.getHeroes:

export class HomeComponent {

      public data: any = {};
      constructor(public modelService: ModelService) {
        // we need the data synchronously for the client to set the server response
        // we create another method so we have more control for testing
        this.universalInit();
      }

      public universalInit() {

        this.modelService.getStuff().subscribe((data) => {
          this.data = data;
        });
      }

I'm getting this error:

GET /src/backend/heroes.json 404 3.698 ms - 46
404 -  {"status":404,"message":"No Content"}
EXCEPTION: 404 -  {"status":404,"message":"No Content"}

/private/var/root/vepo/node_modules/rxjs/Subscriber.js:227
            throw err;
            ^
404 -  {"status":404,"message":"No Content"}
[nodemon] app crashed - waiting for file changes before starting...

So my url private heroesUrl = "http://localhost:4000/src/backend/heroes.json"; // URL to JSON file in the service is wrong. Given that folder structure, what would the url be? Because the actual running project, the output, is in dist:

enter image description here

So I'm not sure what to put in ModelService.heroesUrl. What string value should ModelService.heroesUrl have?

3 Answers 3

8

I put my the same file places.json to "assets" folder and after set the url like:

places = this.http.request("http://localhost:4200/assets/places.json")

hope this info will helpful for somebody.

Sign up to request clarification or add additional context in comments.

Comments

4

you have to put your json file into you dist folder client and you have to change your url to http://localhost:4000/dist/heroes.json<-- destination where you are putting your json file in dist directory

6 Comments

to test if your http working fine you can use jsonplaceholder.typicode.com
Thanks for the testing link. I was thinking that we don't really touch dist and it is just an output after compiling and transpiling the src app. Putting the json in the client doesn't seem right because the whole point of this poc is to get data from the backend, to test connectivity between the back and front end.
after creation of dist folder we have to change our all link also like for image. because when we upload our dist content on server we also have to store local image there. faced this issue so many time. Actually your json should be in server.
actually the dist folder is destroyed and remade every time I build my project. I'm not really sure why, as this is the Angular Universal starter app. I'm still trying to wrap my head around how it works. But it deletes my json file from dist when i compile so it's safe to say that is not an option
@Beniamino_Baggins no problem :) if someone else has a better way then i will also get something to learn and yes its true angular universal each time recreate a dist folder. it have to recreate all the content in dist folder to update its content there is no other folder. its a minified version for production. once it is uploaded on server then you can put your images or json in there.
|
0

Add your directory with the mock data to the "assets" part in angular-cli.json.

Comments

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.