服务之间的交互

时间:2019-03-02 05:32:59

标签: angular

我有三个组件:分页器组件-应用程序组件-和表组件。我使用了表格组件中的材料,并在ts中使用了它。用于排序和搜索的表。在应用程序中,有一个表格数据组件。在分页器组件中。我用这种材料进行布局。但是组件之间的关系存在问题。因此,我可以与包含代码每一部分的这些组件进行通信。

app.componenet.ts

EditTexts

app.component.html

 import { Component, OnInit, ViewChild, Output, Input } from '@angular/core'; 
 import { MatTableDataSource, PageEvent } from
     '@angular/material'; 
 import { MatTableModule } from
     '@angular/material/table'; 

 @Component({   selector: 'app-root',  
                templateUrl: './app.component.html',
                styleUrls:['./app.component.css'] 
 })
 export class AppComponent {   
    student:Stu[] = [{ name: 'ali', family: 'qolami', score: 16 }, ]; 
 } 
 export class Stu {   
    name: string;   
    family: string;   
    score: number; 
 }

paginator.component.html

   <app-table [student]="student"></app-table>

paginator.component.ts

    <mat-paginator #paginator [length]="length" [pageSize]="pageSize"
     [pageSizeOptions]="pageSizeOptions"></mat-paginator>

table.component.ts

  import { Component, OnInit, Input, ViewChild, Output, EventEmitter } from '@angular/core'; 
  import { MatPaginator, PageEvent } from '@angular/material/paginator'; 
  import { MatTableDataSource } from '@angular/material';

  @Component({   
    selector: 'app-paginator',  
    templateUrl:'./paginator.component.html',   
    styleUrls: ['./paginator.component.css'] 
  }) 
  export class PaginatorComponent implements OnInit {   
     @Input() student;   
     length = 5;   
     pageSize = 10;
     pageSizeOptions: number[] = [5, 10, 15, 20];  
     @ViewChild(MatPaginator) paginator: MatPaginator;   
     dataSource;  
     @Output() pageChange = new EventEmitter<number>();   

     constructor() { }

     ngOnInit() {
         this.dataSource = new MatTableDataSource(this.student);
         this.dataSource.paginator = this.paginator;  
     } 
  }

1 个答案:

答案 0 :(得分:1)

如果我理解正确,那么您可以在官方文档LINK

中找到所需的内容。

为方便起见,这里有个小摘要:

与受试者的服务交流可以通过以下方式实现:

在您的服务类(MyService)中,您需要创建一个新的主题(也可以是行为主题或重放主题)。

private mySubject = new Subject<string>();

getMySubject() { return this.mySubject; }

updateMySubject(nextString: string) { this.mySubject.next(nextString) }

可以(通过构造函数)在导入的每个组件中访问该主题

constructor(private myService: MyService) {}

ngOnInit() { 
   myService.getMySubject.subscribe(
      // do something with the value here
   });
}

因此,每次您更新服务的价值时,就会调用此名称。

myService.updateMySubject("this is the new string");

希望这是您所期望的。有关更多信息,请参阅我上面引用的官方文档。

相关问题