从angular 7中的其他组件或服务刷新mat数据源

从angular 7中的其他组件或服务刷新mat数据源,angular,reactjs,typescript,angular-material,angular7,Angular,Reactjs,Typescript,Angular Material,Angular7,我有两个组件,即项目和项目列表,然后是项目服务。 project.component.ts有表单要提交,project.list1.component.ts显示项目列表 当我在project.component.ts中提交项目表单时,我希望刷新可MatDatasourcetable的project.list1.component listData。我试图在提交表单后从project.component.ts调用服务方法refreshList()或getProjectList(),但它没有刷新li

我有两个组件,即项目和项目列表,然后是项目服务。 project.component.ts有表单要提交,project.list1.component.ts显示项目列表

当我在project.component.ts中提交项目表单时,我希望刷新可MatDatasourcetable的project.list1.component listData。我试图在提交表单后从project.component.ts调用服务方法refreshList()或getProjectList(),但它没有刷新listData。此外,我还按照其他人的建议注入了ChangeDetectorRef,但这也不会刷新matdatasource。有些事情我还没弄清楚。每当我立即提交/更新时,项目列表必须刷新并显示更新的列表记录

project.component.ts

import { Component, OnInit, Input, ChangeDetectorRef, ViewChild, ElementRef, EventEmitter, Output } from '@angular/core';
import { MatTableDataSource } from '@angular/material';
import { ProjectService } from 'src/app/shared/project.service';
import { ToastrService } from 'ngx-toastr';
import { NgForm} from '@angular/forms';
import { ProjectModel } from 'src/app/shared/project.model';
import { Observable } from 'rxjs';
import { UserService } from 'src/app/users/user.service';
import { User } from 'src/app/users/user.model';
import { DOCUMENT } from '@angular/common';
import { ModalDirective } from 'ngx-bootstrap/modal';

@Component({
  selector: 'app-project',
  templateUrl: './project.component.html',
  styleUrls: ['./project.component.css']
})
export class ProjectComponent implements OnInit {

  constructor(private service: ProjectService,private changeDetectorRef: ChangeDetectorRef,private toastr: ToastrService, private userService: UserService) { }

    isValidDate: any;
    error:any={isError:false,errorMessage:''};
    minDate: Date;
    IsChecked:boolean;

  ngOnInit() {
    this.resetForm(); 
  }
  resetForm(form?: NgForm) {
    if (form != null)
      form.resetForm();
    this.service.formData = {
      ProjectID: null,
      ProjectName: '',
      StartDate:null ,
      EndDate:null              
    }         
  }

  onSubmit(form: NgForm) {    
      if (form.value.ProjectID == null)    
        this.insertRecord(form);
      else
        this.updateRecord(form);   
  }

  insertRecord(form: NgForm) {
    this.service.postProject(form.value).subscribe(res => {
      this.toastr.success('Inserted successfully', 'Project. Register');
      this.resetForm(form);
      //this.service.refreshList(); 
      //this.service.getProjectList();
    });
   this.changeDetectorRef.detectChanges();
  }

  updateRecord(form: NgForm) {
    this.service.putProject(form.value).subscribe(res => {
      this.toastr.info('Updated successfully', 'Project. Register');
      this.resetForm(form);
      //this.service.refreshList();
      //this.service.getProjectList();           
    });
    this.changeDetectorRef.detectChanges();
  }   
}
import { Component, OnInit, ViewChild, HostBinding } from '@angular/core';
import { ProjectService } from 'src/app/shared/project.service';
import { MatTableDataSource,MatSort,MatPaginator } from '@angular/material';
import { ProjectModel } from 'src/app/shared/project.model';
import { ToastrService } from 'ngx-toastr';

@Component({
  selector: 'app-project-list1',
  templateUrl: './project-list1.component.html',
  styleUrls: ['./project-list1.component.css']
})
export class ProjectList1Component implements OnInit {

  constructor(private service: ProjectService,
    private toastr: ToastrService) { }     

  listData: MatTableDataSource<any>;
  displayedColumns: string[] = ['ProjectName', 'StartDate', 'EndDate'];
  @ViewChild(MatSort,null) sort: MatSort;
  @ViewChild(MatPaginator,null) paginator: MatPaginator;
  searchKey: string;

  ngOnInit() {  
    this.refreshList();          
  }

  refreshList(){
    this.service.getProjectList().subscribe(data =>{    
      this.listData = new MatTableDataSource(data);
      this.listData.sort = this.sort;
      this.listData.paginator = this.paginator;
    });
  } 
}
import { Injectable } from '@angular/core';
import { ProjectModel } from './project.model';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ProjectService {
  formData  : ProjectModel;
  list : ProjectModel[];
  readonly rootURL ="http://localhost:65462/api"

  constructor(private http: HttpClient) { }

  postProject(formData : ProjectModel){
    console.log(formData);  
    return this.http.post(this.rootURL+'/Project',formData);     
   }

   getProjectList(): Observable<ProjectModel[]>{
     return this.http.get<ProjectModel[]>(this.rootURL+'/Project/');
   }

   refreshList(){
     return this.http.get(this.rootURL+'/Project')
     .toPromise().then(res => this.list = res as ProjectModel[]);
    }

  }
project-list1.component.ts

import { Component, OnInit, Input, ChangeDetectorRef, ViewChild, ElementRef, EventEmitter, Output } from '@angular/core';
import { MatTableDataSource } from '@angular/material';
import { ProjectService } from 'src/app/shared/project.service';
import { ToastrService } from 'ngx-toastr';
import { NgForm} from '@angular/forms';
import { ProjectModel } from 'src/app/shared/project.model';
import { Observable } from 'rxjs';
import { UserService } from 'src/app/users/user.service';
import { User } from 'src/app/users/user.model';
import { DOCUMENT } from '@angular/common';
import { ModalDirective } from 'ngx-bootstrap/modal';

@Component({
  selector: 'app-project',
  templateUrl: './project.component.html',
  styleUrls: ['./project.component.css']
})
export class ProjectComponent implements OnInit {

  constructor(private service: ProjectService,private changeDetectorRef: ChangeDetectorRef,private toastr: ToastrService, private userService: UserService) { }

    isValidDate: any;
    error:any={isError:false,errorMessage:''};
    minDate: Date;
    IsChecked:boolean;

  ngOnInit() {
    this.resetForm(); 
  }
  resetForm(form?: NgForm) {
    if (form != null)
      form.resetForm();
    this.service.formData = {
      ProjectID: null,
      ProjectName: '',
      StartDate:null ,
      EndDate:null              
    }         
  }

  onSubmit(form: NgForm) {    
      if (form.value.ProjectID == null)    
        this.insertRecord(form);
      else
        this.updateRecord(form);   
  }

  insertRecord(form: NgForm) {
    this.service.postProject(form.value).subscribe(res => {
      this.toastr.success('Inserted successfully', 'Project. Register');
      this.resetForm(form);
      //this.service.refreshList(); 
      //this.service.getProjectList();
    });
   this.changeDetectorRef.detectChanges();
  }

  updateRecord(form: NgForm) {
    this.service.putProject(form.value).subscribe(res => {
      this.toastr.info('Updated successfully', 'Project. Register');
      this.resetForm(form);
      //this.service.refreshList();
      //this.service.getProjectList();           
    });
    this.changeDetectorRef.detectChanges();
  }   
}
import { Component, OnInit, ViewChild, HostBinding } from '@angular/core';
import { ProjectService } from 'src/app/shared/project.service';
import { MatTableDataSource,MatSort,MatPaginator } from '@angular/material';
import { ProjectModel } from 'src/app/shared/project.model';
import { ToastrService } from 'ngx-toastr';

@Component({
  selector: 'app-project-list1',
  templateUrl: './project-list1.component.html',
  styleUrls: ['./project-list1.component.css']
})
export class ProjectList1Component implements OnInit {

  constructor(private service: ProjectService,
    private toastr: ToastrService) { }     

  listData: MatTableDataSource<any>;
  displayedColumns: string[] = ['ProjectName', 'StartDate', 'EndDate'];
  @ViewChild(MatSort,null) sort: MatSort;
  @ViewChild(MatPaginator,null) paginator: MatPaginator;
  searchKey: string;

  ngOnInit() {  
    this.refreshList();          
  }

  refreshList(){
    this.service.getProjectList().subscribe(data =>{    
      this.listData = new MatTableDataSource(data);
      this.listData.sort = this.sort;
      this.listData.paginator = this.paginator;
    });
  } 
}
import { Injectable } from '@angular/core';
import { ProjectModel } from './project.model';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ProjectService {
  formData  : ProjectModel;
  list : ProjectModel[];
  readonly rootURL ="http://localhost:65462/api"

  constructor(private http: HttpClient) { }

  postProject(formData : ProjectModel){
    console.log(formData);  
    return this.http.post(this.rootURL+'/Project',formData);     
   }

   getProjectList(): Observable<ProjectModel[]>{
     return this.http.get<ProjectModel[]>(this.rootURL+'/Project/');
   }

   refreshList(){
     return this.http.get(this.rootURL+'/Project')
     .toPromise().then(res => this.list = res as ProjectModel[]);
    }

  }
从'@angular/core'导入{Component,OnInit,ViewChild,HostBinding};
从'src/app/shared/project.service'导入{ProjectService};
从“@angular/material”导入{MatTableDataSource,MatSort,MatPaginator};
从'src/app/shared/project.model'导入{ProjectModel};
从“ngx-toastr”导入{ToastrService};
@组成部分({
选择器:“app-project-list1”,
templateUrl:'./project-list1.component.html',
样式URL:['./project-list1.component.css']
})
导出类ProjectList1Component在NIT上实现{
建造商(私人服务:项目服务、,
私人toastr:ToastrService){}
listData:MatTableDataSource;
displayedColumns:string[]=['ProjectName','StartDate','EndDate'];
@ViewChild(MatSort,null)排序:MatSort;
@ViewChild(MatPaginator,null)分页器:MatPaginator;
搜索键:字符串;
ngOnInit(){
这个.refreshList();
}
刷新列表(){
this.service.getProjectList().subscribe(数据=>{
this.listData=新MatTableDataSource(数据);
this.listData.sort=this.sort;
this.listData.paginator=this.paginator;
});
} 
}
project-list1.component.html

  <mat-table [dataSource]="listData" matSort>

项目服务.ts

import { Component, OnInit, Input, ChangeDetectorRef, ViewChild, ElementRef, EventEmitter, Output } from '@angular/core';
import { MatTableDataSource } from '@angular/material';
import { ProjectService } from 'src/app/shared/project.service';
import { ToastrService } from 'ngx-toastr';
import { NgForm} from '@angular/forms';
import { ProjectModel } from 'src/app/shared/project.model';
import { Observable } from 'rxjs';
import { UserService } from 'src/app/users/user.service';
import { User } from 'src/app/users/user.model';
import { DOCUMENT } from '@angular/common';
import { ModalDirective } from 'ngx-bootstrap/modal';

@Component({
  selector: 'app-project',
  templateUrl: './project.component.html',
  styleUrls: ['./project.component.css']
})
export class ProjectComponent implements OnInit {

  constructor(private service: ProjectService,private changeDetectorRef: ChangeDetectorRef,private toastr: ToastrService, private userService: UserService) { }

    isValidDate: any;
    error:any={isError:false,errorMessage:''};
    minDate: Date;
    IsChecked:boolean;

  ngOnInit() {
    this.resetForm(); 
  }
  resetForm(form?: NgForm) {
    if (form != null)
      form.resetForm();
    this.service.formData = {
      ProjectID: null,
      ProjectName: '',
      StartDate:null ,
      EndDate:null              
    }         
  }

  onSubmit(form: NgForm) {    
      if (form.value.ProjectID == null)    
        this.insertRecord(form);
      else
        this.updateRecord(form);   
  }

  insertRecord(form: NgForm) {
    this.service.postProject(form.value).subscribe(res => {
      this.toastr.success('Inserted successfully', 'Project. Register');
      this.resetForm(form);
      //this.service.refreshList(); 
      //this.service.getProjectList();
    });
   this.changeDetectorRef.detectChanges();
  }

  updateRecord(form: NgForm) {
    this.service.putProject(form.value).subscribe(res => {
      this.toastr.info('Updated successfully', 'Project. Register');
      this.resetForm(form);
      //this.service.refreshList();
      //this.service.getProjectList();           
    });
    this.changeDetectorRef.detectChanges();
  }   
}
import { Component, OnInit, ViewChild, HostBinding } from '@angular/core';
import { ProjectService } from 'src/app/shared/project.service';
import { MatTableDataSource,MatSort,MatPaginator } from '@angular/material';
import { ProjectModel } from 'src/app/shared/project.model';
import { ToastrService } from 'ngx-toastr';

@Component({
  selector: 'app-project-list1',
  templateUrl: './project-list1.component.html',
  styleUrls: ['./project-list1.component.css']
})
export class ProjectList1Component implements OnInit {

  constructor(private service: ProjectService,
    private toastr: ToastrService) { }     

  listData: MatTableDataSource<any>;
  displayedColumns: string[] = ['ProjectName', 'StartDate', 'EndDate'];
  @ViewChild(MatSort,null) sort: MatSort;
  @ViewChild(MatPaginator,null) paginator: MatPaginator;
  searchKey: string;

  ngOnInit() {  
    this.refreshList();          
  }

  refreshList(){
    this.service.getProjectList().subscribe(data =>{    
      this.listData = new MatTableDataSource(data);
      this.listData.sort = this.sort;
      this.listData.paginator = this.paginator;
    });
  } 
}
import { Injectable } from '@angular/core';
import { ProjectModel } from './project.model';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ProjectService {
  formData  : ProjectModel;
  list : ProjectModel[];
  readonly rootURL ="http://localhost:65462/api"

  constructor(private http: HttpClient) { }

  postProject(formData : ProjectModel){
    console.log(formData);  
    return this.http.post(this.rootURL+'/Project',formData);     
   }

   getProjectList(): Observable<ProjectModel[]>{
     return this.http.get<ProjectModel[]>(this.rootURL+'/Project/');
   }

   refreshList(){
     return this.http.get(this.rootURL+'/Project')
     .toPromise().then(res => this.list = res as ProjectModel[]);
    }

  }
从'@angular/core'导入{Injectable};
从“./project.model”导入{ProjectModel};
从'@angular/common/http'导入{HttpClient};
从“rxjs”导入{Observable};
@注射的({
providedIn:'根'
})
导出类项目服务{
formData:ProjectModel;
列表:ProjectModel[];
只读根URL=”http://localhost:65462/api"
构造函数(私有http:HttpClient){}
后期项目(formData:ProjectModel){
console.log(formData);
返回this.http.post(this.rootURL+'/Project',formData);
}
getProjectList():可观察{
返回this.http.get(this.rootURL+'/Project/');
}
刷新列表(){
返回this.http.get(this.rootURL+'/Project')
.toPromise()。然后(res=>this.list=res as ProjectModel[]);
}
}

您应该在
项目.service.ts
中使用observable,以便更轻松地订阅更改。例如

export class ProjectService {
  formData  : ProjectModel;
-->  list$ : BehaviorSubject<ProjectModel[]> = new BehaviorSubject([]);
  readonly rootURL ="http://localhost:65462/api"

  constructor(private http: HttpClient) { }

  postProject(formData : ProjectModel){
    console.log(formData);  
    return this.http.post(this.rootURL+'/Project',formData);     
   }

   getProjectList(): Observable<ProjectModel[]>{
     return this.http.get<ProjectModel[]>(this.rootURL+'/Project/');
   }

   refreshList(){
     return this.http.get(this.rootURL+'/Project')
-->     .toPromise().then(res => this.list$.next(res));
    }

  }

您还应该确保在该组件被销毁后取消订阅

太多代码,您是否可以共享slackblitz URL是的,这对我帮助不大。在订阅list$之前,我需要从服务中调用refreshList。谢谢。