如何将值从组件类传递到子类?

时间:2017-10-26 16:20:49

标签: angular typescript

我有类似下面的打字稿文件,它在单个文件中有三个类。 我试图将值从MainComponent类传递给TableContent类。

所以我在TableContent类中尝试super()它没有帮助,然后尝试@Injectable它也会抛出错误。

有人可以告诉我如何将此值从MainComponent班级传递给TableContent班级。我需要访问MainComponent类中的值。

main.component.ts

@Component({
  templateUrl: './main.component.html'
})
export class MainComponent implements OnInit {
    public PassThisChild:any;
    public dataTable: any[];
    public sortedData;

    public displayedColumns = ['userId', 'userName', 'progress', 'color'];
    public tableContent = new TableContent();
    public dataSource: TableControlClass | null;
    @ViewChild(MatSort) public sort: MatSort;
    @ViewChild('filter') public filter: ElementRef;

    constructor(private _apiService: ApiService) {
      this._apiService.getTableData()
      .subscribe(
                data => {
                  this.PassThisChild = data;  // i want to pass this
                },
                error => {
                  console.log(error);
                }
              );
    }

    public ngOnInit() {
      this.dataSource = new TableControlClass(this.tableContent, this.sort);
      Observable.fromEvent(this.filter.nativeElement, 'keyup')
      .debounceTime(150)
      .distinctUntilChanged()
      .subscribe(() => {
        if (!this.dataSource) { return; }
        this.dataSource.filter = this.filter.nativeElement.value;
      });
    }
}

    const COLORS = ['maroon', 'red', 'orange', 'yellow', 'olive', 'green', 'purple',
    'fuchsia', 'lime', 'teal', 'aqua', 'blue', 'navy', 'black', 'gray'];
    const NAMES = ['Maia', 'Asher', 'Olivia', 'Atticus', 'Amelia', 'Jack',
    'Charlotte', 'Theodore', 'Isla', 'Oliver', 'Isabella', 'Jasper',
    'Cora', 'Levi', 'Violet', 'Arthur', 'Mia', 'Thomas', 'Elizabeth'];

    export interface UserData {
          id: string;
          name: string;
          progress: string;
          color: string;
    }

export class TableContent {
  public storeHere:any;   // Here i want to access 
  public dataChange: BehaviorSubject<UserData[]> = new BehaviorSubject<UserData[]>([]);
    get data(): UserData[] { return this.dataChange.value; }
      constructor() {
        for (let i = 0; i < 6; i++) { this.addUser(); }
    }
    private addUser() {
      const copiedData = this.data.slice();
      copiedData.push(this.createNewUser());
      this.dataChange.next(copiedData);
    }
    private createNewUser() {
      const name =
          NAMES[Math.round(Math.random() * (NAMES.length - 1))] + ' ' +
          NAMES[Math.round(Math.random() * (NAMES.length - 1))].charAt(0) + '.';
      return {
        id: (this.data.length + 1).toString(),
        name: name,
        progress: Math.round(Math.random() * 100).toString(),
        color: COLORS[Math.round(Math.random() * (COLORS.length - 1))]
      };
    }
}

export class TableControlClass extends DataSource<any> {
  public _filterChange = new BehaviorSubject('');
  get filter(): string { return this._filterChange.value; }
  set filter(filter: string) { this._filterChange.next(filter); }

  private filteredData: UserData[] = [];

  constructor(private _tableContent: TableContent, private _sort: MatSort) {
    super();
  }
  public connect(): Observable<UserData[]> {
  const displayDataChanges = [this._tableContent.dataChange, this._filterChange, this._sort.sortChange];

  return Observable.merge(...displayDataChanges).map(() => {
    // Filter data
    this.filteredData = this._tableContent.data.slice().filter((item: UserData) => {
      let searchStr = (item.name + item.color).toLowerCase();
      return searchStr.indexOf(this.filter.toLowerCase()) !== -1;
    });

    return this.sortData(this.filteredData.slice());
  });
}

  public disconnect() { }

  public sortData(data: UserData[]): UserData[] {
    if (!this._sort.active || this._sort.direction === '') { return data; }
    return data.sort((a, b) => {
      let propertyA: number|string = '';
      let propertyB: number|string = '';
      switch (this._sort.active) {
        case 'userId': [propertyA, propertyB] = [a.id, b.id]; break;
        case 'userName': [propertyA, propertyB] = [a.name, b.name]; break;
        case 'progress': [propertyA, propertyB] = [a.progress, b.progress]; break;
        case 'color': [propertyA, propertyB] = [a.color, b.color]; break;
      }
      let valueA = isNaN(+propertyA) ? propertyA : +propertyA;
      let valueB = isNaN(+propertyB) ? propertyB : +propertyB;
      return (valueA < valueB ? -1 : 1) * (this._sort.direction === 'asc' ? 1 : -1);
    });
  }
}

有人可以告诉我如何将此值从MainComponent班级传递给TableContent班级。我需要访问MainComponent类构造函数中的值。

1 个答案:

答案 0 :(得分:0)

如果您在初始化时尝试将this.PassThisChild传递给TableContent类,可以像这样在_apiService订阅块中移动TableControllerClass创建代码 -

// class MainComponent

this._apiService.getTableData().subscribe(data => {
    this.PassThisChild = data;
    this.tableContent = new TableContent(this.PassThisChild);
    this.dataSource = new TableControlClass(this.tableContent, this.sort);
  },
  error => {
    console.log(error);
  });

// class TableContent 

export class TableContent {
  constructor(public storeHere){}
}