3

I have a json file and I'm trying to put this information in my project with a service in Angular 2. Here is my code:

That is my service:

import { Injectable } from '@angular/core';
import { Http, Response} from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class RecordsService {

data: any;

  constructor(private http: Http) { }

  getRecords(id) {
 return this.http.get('../assets/data/03_data.json')
      .map(data => {
        this.data = data;
      }, err => {
        if (err) {
          return err.json();
        }
      });
  }

}

That is the component:

import { Component, OnInit } from '@angular/core';
import { RecordsService } from '../shared/services/records.service';

@Component({
  selector: 'app-content',
  templateUrl: './content.component.html',
  styleUrls: ['./content.component.css'],
  providers: [RecordsService]
})
export class ContentComponent implements OnInit {

  constructor(private recService: RecordsService) { }

  ngOnInit() {
  }

  getRecords(id) {
    this.recService.getRecords(id)
      .subscribe(data => {
      console.log(data);
      }, err => {
        console.log(err);
      });
  }

}

Can someone help me what I did wrong. Thanks!

2 Answers 2

2

You are not calling getRecords() anywhere so it will not be fired at all. We found out that the id wasn't supposed to be a parameter in getRecords() at all. So call the method in OnInit:

ngOnInit() {
   this.getRecords();
}

also you need to return the actual json from the response, i.e .json() so do:

.map(data => {
   this.data = data.json();
   return data.json();
}
Sign up to request clarification or add additional context in comments.

Comments

1

You need to return something from your map statement:

.map(data => {
        this.data = data;
        return data;
      }

11 Comments

I haven't nothing in the console again. :(
probably should be data.json() ;)
@vesselinivanov when you check your network tab in developer tools, do you see the response?
@echonax nope I didn't see a response for my service.
@AJT_82 I called getRecord() in my component: this.recService.getRecords(id)
|

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.