如何在 angular 中显示搜索结果 4

How to show search result in angular 4

我有一个过滤器组件,其中有 2 个字段可用于过滤目录列表和一个搜索按钮。

我想在显示所有目录列表的主组件中显示过滤结果。

实际上一切正常,当我单击搜索按钮时,在 filter.component.ts 文件中搜索函数 运行 并从 api 中获取结果并在控制台中显示结果。但我无法将结果传递给必须显示筛选列表的主要组件。

没有看到任何代码示例。我希望您只是过滤已经获取的数据。如果它确实需要你获取另一组数据,你需要将该数据发送回父组件。

有很多方法可以做到这一点。使用 @Output 向父组件发出函数。或者使用服务和 Observable。

这是您在使用服务时要求的示例。 https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service

// test.service.ts
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/subject';

@Injectable()
export class TestService {

  // Source
  private list = new Subject<Object[]>();

  // Observable Stream
  public list$ = this.list.asObservable();

  constructor() {}

  updateList(data) {
    this.list.next(data);
  }
}

// parent.component.ts
import { Component, OnInit } from '@angular/core';
import { TestService } from 'services/test.service.ts';

@Component({
  selector: 'parent-name',
  templateUrl: 'parent.component.html',
  providers: []
})

export class ParentComponent implements OnInit {
  list;

  constructor(
    private testService: TestService
  ) {
    testService.list$.subscribe(data => {
      this.list = data;
    });
  }

  ngOnInit() { }
}

// child.component.ts
import { Component, OnInit } from '@angular/core';
import { TestService } from 'services/test.service.ts';

@Component({
  selector: 'child-name',
  templateUrl: 'child.component.html'
})

export class ChilComponent implements OnInit {
  list;

  constructor(
    private testService: TestService
  ) { }

  ngOnInit() { }

  update(){
    this.testService.updateList(list);
  }
}