Angular - 使用@Output和Promises回调父组件

时间:2017-08-07 12:01:24

标签: angular

我希望能够订阅子组件的onSearch @Output,以便在子组件中执行搜索时,在父组件中处理从搜索返回数据的承诺。有没有办法在Angular中做到这一点?我试过在onSearch上创建一个@Input,这对于返回一个承诺是有效的,但是"这个" scope是子组件。所以我认为它必须是@oOutput

@Component({
  selector: 'child-component-search',
  templateUrl: './child-component.html'
})
export class ChildSearchComponent{
  public data : any = new Array();
  @Output() onSearch: any = new EventEmitter();
  search(form: any) {
      let self = this
      this.onSearch.emit({searchText:"Text"}).then(res=>{
        self.data = res;
      },rej=>{})
  }
}

@Component({
  selector: 'parent-component-search',
  template: `
    <child-component-search (onSearch)="search($event)"></child-component-search>
  `
})
export class ParentComponent{
  constructor(public service: MyService){}
  search(search: any) {
      let self = this
      return new Promise((resolve,reject)=>{
        this.service(search.searchText).then(res=>{
            resolve(res)
        },rej=>{})
      })
}

2 个答案:

答案 0 :(得分:0)

子组件

@Component({
  selector: 'child-component-search',
  templateUrl: './child-component.html'
})
export class ChildSearchComponent{
  @Input() data; // use this data in the template
  @Output() onSearch = new EventEmitter<{searchText:string}>();

  search(form: any) {
      this.onSearch.emit({searchText:"Text"});
  }
}

父组件

@Component({
  selector: 'parent-component-search',
  template: `
    <child-component-search (onSearch)="search($event)" [data]='data'>
    </child-component-search>
  `
})
export class ParentComponent {
  data:any[] = [];

  constructor(public service: MyService){}

  search(search: any) {
      return new Promise((resolve,reject)=>{
        this.service(search.searchText).then( res =>{
            this.data = res; // assuming the service will return array
        });
      })
}

我使用来自父级的数据作为子组件中的输入,并且当子组件搜索您发出的搜索了Text的事件时,然后在父组件中处理它并更新数据属性以孩子为输入。

换句话说,

家长 =&gt;输入(数据)=&gt; 孩子
儿童 =&gt; emit(search)=&gt;
//更新输入(数据)并将其反映出来  孩子。

答案 1 :(得分:0)

我通过传递一个回调函数来实现这一点:

@Component({
  selector: 'child-component-search',
  templateUrl: './child-component.html'
})
export class ChildSearchComponent{
  public data : any = new Array();

  @Input() onSearch: Function;
  search(form: any) {

      this.onSearch({searchText:"Text"}, res => {
        this.data = res;
      });
  }
}

@Component({
  selector: 'parent-component-search',
  template: `
    <child-component-search [onSearch]="onSearch"></child-component-search>
  `
})
export class ParentComponent{
  constructor(public service: MyService){}

  onSearch = (search: any, callback) => {

      this.service(search.searchText).then(res=>{
          callback(res)
      },rej=>{});
  }
}