Angular 4 Data in service, passing component (s)

Have some data in the service and it worked fine when I had data in an object sitting on the service, but now that I have connected a database connection, the data never gets into the component.

I want the service to subscribe to the data returned from the database and define 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 feature mapPersonFrominput()

is the delay from the mocked data. this is essentially the same as extractData below, but from a static object in 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 just assigns values ​​from the input object to the service object structure, and handleerror just logs the error to the console.

I am calling the service to initialize the data object from the component before the component is loaded by calling this function from the navigation component:

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

      

and in the actual component that needs to receive the data, I am using ngOnInit, but I think I should be using ngOnChanges to initialize the component. Here is the code I'm currently using but haven't had time to fix it yet.

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

      

getName()

just returns the object that I store in the service.

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

      

+3


source to share


1 answer


You shouldn't be using here ngOnChanges

, that doesn't mean what you're trying to do.

As per your question, this is what you are trying to achieve:

  • Retrieving data from the database
  • Your component should be able to receive some of this data asynchronously.

You can achieve this with the code you have. All you have to do is add a little more code and use RxJS. More specific:

  • Create a person theme in your personal service
  • When data is returned from your DB, do personSubject.next(dataFromDB)

    to add to the user thread.
  • Create a function that will return the human subject as an observable, and then you can subscribe to what can be observed from your component.


With this approach, every time data comes from your DB, that data will be added to the user stream, and everything that subscribes to this stream (your component) will receive the data.

Quick example (since I don't have the complete code):

import { ReplaySubject } from 'rxjs/ReplaySubject';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class PersonService {
    // The person subject
    personStream: ReplaySubject<Person> = new ReplaySubject();

    // The person observable
    person$(): Observable<Person> {
        return this.personStream.asObservable();
    }

    // Get person from DB and add to stream
    getDataFromDB() {
        this.http.get(url).subscribe(response => {
            this.personStream.next(response.person);
        });
    }
}

@Component({...})
export class MyComponent implements OnInit {
    person: Person;

    constructor(private personService: PersonService) {}

    ngOnInit() {
        // Subscribe to person observable. Any time person data changes, this will be called.
        this.personService.person$().subscribe(person => this.person = person);

        // If you return the `this.http.get(url)` from `getDataFromDB`, you can just do this instead...
        this.personService.getDataFromDB().subscribe(person => this.person = person);
    }
}

      

But this is all overkill, because really all you have to do is subscribe to a function getDataFromDB

in your component, since that itself can return the observable type Person.

+4


source







All Articles