简体   繁体   English

Angular 2将ajax调用响应转移到另一个组件

[英]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. 我刚开始使用angular 2玩,遇到一个小问题,我已经搜索了各种形式以及angular文档。

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. 我设法提供了一个可以打电话的服务,然后当我按下按钮以使用dynamicload组件加载另一个组件并可以访问ajax结果时,我想要一个组件。

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. 问题是如何使用Observables或Promises方法使结果在其他组件中可访问。

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. 您的Root组件正在调用服务方法,该方法将为您返回Promise对象。
  2. Then you map needed data from response to the component model inside Root Component constructor. 然后,您可以将所需的数据从响应映射到Root Component构造函数中的组件模型。
  3. And your Child component should be subscribed for the model which you was preparing in previous step. 并且您的Child组件应订阅您在上一步中准备的模型。

     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. 上面只是一个简短示例,说明如何在从promise对象到本地模型的根组件中设置模型。

New research: 新研究:

There is another way to fill your components by data from api's. 还有另一种方法可以通过api的数据填充您的组件。 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. 您可以使用EventEmitter从服务中发出事件,然后可以在创建的组件内部订阅此事件,这样每次调用该服务时,它们都将获取数据。 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 这是一个示例,该示例说明了如何在多个组件之间共享服务ajax数据而不两次发出请求: 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 可以在此处找到完整的工作示例/插件http : //plnkr.co/edit/TR7cAqNATuygDAfj4wno?p=preview

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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