首页 > 解决方案 > 使用角度从另一个组件执行功能时更新组件的更改

问题描述

我有一个学生组件,它在加载页面上显示学生列表。我创建了另一个组件来添加学生,我希望当我点击自动提交时,学生组件将被更改并显示新学生而不刷新页面。为此,在添加学生后,我从服务中调用函数 onGetStudents() 我向您展示了我在下面实现的解决方案,但它不起作用!

@Injectable()
export class myservice {

  constructor(private  httpClient:HttpClient){}

    onGetStudents(){
       return this.httpClient.get("http://localhost:8080/students");
    }
} 



export class StudentsComponent implements OnInit{

   constructor(private  httpClient:HttpClient,private myservice:myservice) { }

     ngOnInit() {
       this.getStudents();
       }

 getStudents(){
    this.myservice.onGetStudents()
      .subscribe(data=>{
        this.listStudents=data;
      },err=>{
        console.log(err);
      });
  }
}



 export class addStudentComponent implements OnInit {
      student:any;
      constructor(private httpClient:HttpClient,private myservice:myservice) { }

      ngOnInit() {
      }

      onSaveStudent(student){
        this.httpClient.post("http://localhost:8080/students",students)
          .subscribe(data=>{
            this.student=data;
            this.myservice.onGetStudents();
          },err=>{
            console.log(err);
          })
      }
    }

PS:我当然在提供者中添加了 myservice 。

标签: angularangular5angular6

解决方案


推荐阅读