简体   繁体   中英

Angular 2 transfer ajax call response to another component

I just started playing with angular 2 and i've ran into a small problem, that i ve searched for in various forms and also angulars documentation.

I've managed to make a service that makes a call and then i want in a component when i press a button to load another component with dynamicload component and have access to the ajax result.

The problem is that I can t figure out how to do that..

The question is how can I make the result accesible in other components using Observables or Promises method.

If I understood correctly your question, you are looking a way to insert a data from request to another nested component.

I hope this image will clarify for you the data flow for this case.

组件互动

  1. Your Root component is calling a service method which returns for you promise object.
  2. Then you map needed data from response to the component model inside Root Component constructor.
  3. And your Child component should be subscribed for the model which you was preparing in previous step.

     ngOnInit() { this.dataService.getSomeData() .subscribe((data: IData) => { this.data = data; }); 

    }

Just a short example above how to set model in the root component from the promise object to the local model.

New research:

There is another way to fill your components by data from api's. You can use EventEmitter to emit event from service, and then, you can subscribe for this event inside you created components, so they will get a data, each time there will be called the service. Here is nice example of this strategy in the first answer. Service Events

Hope it will help you, let me know if you will need additional info!

Just create a service, then inject the service where you want. Here it's an example how to share a service ajax data across many components without making the request twice : https://stackoverflow.com/a/36413003/2681823

the Service:

@Injectable()
export class DataService {
    constructor(private http: Http) { }

    private _dataObs = new ReplaySubject<request>(1); 

    getData(forceRefresh?: boolean) {
    // On Error the Subject will be Stoped and Unsubscribed, if so, create another one
    this._dataObs = this._dataObs.isUnsubscribed ? new ReplaySubject(1) : this._dataObs;

    // If the Subject was NOT subscribed before OR if forceRefresh is requested
    if (!this._dataObs.observers.length || forceRefresh) {
            this.http.get('http://jsonplaceholder.typicode.com/posts/2')
              .subscribe(
                requestData => {
                  this._dataObs.next(requestData);
                },
                error => this._dataObs.error(error));
        }

        return this._dataObs;
    }
}

the Component:

@Component({
  selector: 'child',
  template : `<button (click)="makeRequest()" class="btn">Click me!</button>`
}) 
export class Child {
  constructor(private _dataService: DataService) {  } 

  makeRequest() {
    this._dataService.getData().subscribe( 
      requestData => {
          console.log('ChildComponent', requestData);
      }
  }
}

A full working example/plunker can be found here : http://plnkr.co/edit/TR7cAqNATuygDAfj4wno?p=preview

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM