Angular 4 Data in Service, passing to component(s)

Viewed 8162

Have some data in a service, and was working perfectly when I had data in an object sitting on the service, but now that I've hooked up a database connection, the data never makes it to the component.

I want the service to subscribe to the data coming back from the database and have defined the call like this:

  public setPerson(ac: string): void{
    console.log(ac);
    this.generatePerson(ac).subscribe((data) => {
        // this.mapPersonFromInput(data[0]);
        console.dir(data);
    });

  }

The mapPersonFrominput() function is a holdover from mocked data. it is essentially the same as extractData further below, but from a static object in the code.

generatePerson looks like this:

public generatePerson(id: string):Observable<Person>{
    var datRetUrl: string = '/api/'
    var fullUrl: string = datRetUrl + id;
    return this.http.get(fullUrl)
                .map(this.extractData)
                .catch(this.handleError);
  }

extractData simply assigns values from the input object to the service's object structure, and handleerror simply logs the error to the console.

I call the service to initialize the data object from the component before the component loads by calling this function from a navigation component:

  passCodeToService():void{
    this.psn.setPerson(this.accessCode);
    this.route.navigate(['/name']);
  }

and in the actual component that should get the data, I'm using ngOnInit, but I think I should be using ngOnChanges to initialize the component. Here's the code that I'm currently using, but haven't had luck fixing just yet.

ngOnInit() {
  this.name =this.psn.getName();
  console.log(this.name);
}

getName() simply returns the object that I'm storing in the service.

  public getName(): Name{
    return this.servicePerson.name;
  }
1 Answers
Related