简体   繁体   English

从组件到服务进行ajax调用并访问来自另一个组件的响应

[英]Making ajax call from a component to a service and access response from another component

I am learning Angular2 by creating an example where I want to have a button click on Component1 that makes an ajax call to a Service and the response of the ajax should be used and displayed in another component.我正在通过创建一个示例来学习 Angular2,我希望在 Component1 上单击一个按钮,该按钮对服务进行 ajax 调用,并且应该在另一个组件中使用和显示 ajax 的响应。

在此处输入图片说明

I am able to create the Component1 and able to get the response by making ajax call in Service class.我能够创建 Component1 并能够通过在 Service 类中进行 ajax 调用来获得响应。 Now how can I display the result in another component现在如何在另一个组件中显示结果

This is my first component:这是我的第一个组件:

import { Component } from '@angular/core';
import { ProfileService } from '../shared/index';

@Component({
  selector: 'home-page',
  template: `
  <div>
    <button (click)="loadUser()">Load profile</button>
    {{ profile | json }}
  </div>
  `
})
export class ProfileComponent {
  constructor(private profileService: ProfileService) {}
  profile = {};

  loadUser() {
    this.profileService.getUser().subscribe(data => this.profile = data);
  }
}

This is my service class:这是我的服务类:

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

@Injectable()
export class ProfileService {
  constructor (
    private http: HttpClient
  ) {}

  getUser() {
   return this.http.get(`https://conduit.productionready.io/api/profiles/eric`)
    .map(res => res );
  }

}

This is my second component where I want to see the result:这是我想要查看结果的第二个组件:

import { Component } from '@angular/core';

@Component({
  selector: 'result-page',
  template: `
  <div>Result Page :     
    {{ profile | json }}
  </div>
  `
})
export class ResultComponent {
  constructor(private profileService: ProfileService) {}
  profile = {};
  username = "";
  bio = "";
}

Basically the ajax response is a Json content, I want to store whole json in profile file.基本上 ajax 响应是一个 Json 内容,我想将整个 json 存储在profile文件中。 This json contains fields for username and bio, I want to store them in my variables username and bio of my result component.这个 json 包含 username 和 bio 的字段,我想将它们存储在我的结果组件的变量 username 和 bio 中。

I am stuck how to build my result component, can you please help me.我被困在如何构建我的结果组件中,你能帮我吗。

I am want to communicate between components, don't want to use any routers here.我想在组件之间进行通信,不想在这里使用任何路由器。

The json response is : json 响应是:

{
"profile": {
"username": "eric",
"bio": "Cofounder of Thinkster.io, kinda looks like Peeta from the Hunger Games",
"image": "http://i.imgur.com/S66L2XZ.jpg",
"following": false
}
}

Edit: If the component you are trying to pass the data to is the child of that component you can use the @Input decorator to pass the data to it.编辑:如果您尝试将数据传递给的组件是该组件的子组件,您可以使用 @Input 装饰器将数据传递给它。 The @Input will automatically register the changes and update the template. @Input 将自动注册更改并更新模板。 If you need to do any update functions when this input changes you can use ngOnChanges, but if you are simple displaying the changes you can just use the @Input and it will update the view accordingly.如果您需要在此输入更改时执行任何更新功能,您可以使用 ngOnChanges,但如果您只是简单地显示更改,您可以只使用 @Input,它会相应地更新视图。

If the two components are both children of a shared parent you can use the @Ouput decorator on the component1 to output the data to the parent and set the variable that is being passed into the Input of the other.如果两个组件都是共享父级的子级,则可以使用 component1 上的 @Ouput 装饰器将数据输出到父级并设置正在传递到另一个 Input 的变量。

in results component在结果组件中

export class ResultComponent implements OnChanges {
  @Input results: any;

  constructor(private profileService: ProfileService) {}

  ngOnChanges(changes: SimpleChanges) {
    if(changes['profile'] && changes['profile'].currentValue){
       // do any update functions here if needed
    }
  }
  profile = {};
  username = "";
  bio = "";
} 

and in the profile template并在配置文件模板中

<results-page [profile]="profile"></results-page>

in component1 if that component is also a child在 component1 中,如果该组件也是子组件

export class ProfileComponent {

  @Ouput() emitProfile = new EventEmitter<any>()

  constructor(private profileService: ProfileService) {}
  profile = {};

  loadUser() {
    this.profileService.getUser().subscribe(data => this.profile = data);
  }
}

and then in the parent you would handle the data emit like so:然后在父级中,您将像这样处理数据发出:

handleEmitProfile(profile) { this.profile = profile }

option 2 - add another function in the service.选项 2 - 在服务中添加另一个功能。

@Injectable()
export class ProfileService {
  constructor (
    private http: HttpClient
  ) {}

  private profile$ = new Subject();

  getUser() {
    return this.http.get(`https://conduit.productionready.io/api/profiles/eric`)    .map(res => res );
  }

  returnProfile() {
     return this.profile$;
  }

  updateProfileObject(event) {
    this.profile$.next(event);
  }
}

in your results component add this:在您的结果组件中添加以下内容:

this.profileService.returnProfile().subscribe(event => this.profile = event}

and in your profile component并在您的个人资料组件中

this.profileService.updateProfileObject(this.profile);

and that function will update the profile$ variable in the service calling the function in the results component.并且该函数将更新调用结果组件中的函数的服务中的 profile$ 变量。

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

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