更新数据而不在URL中传递id参数

时间:2018-10-23 05:28:25

标签: angular

我正在Angular材质对话框中执行编辑操作。我能够将数据(id和data-key)发送到对话框。在对话框中,我绑定了组件发送的数据。绑定之后,我需要编辑该预填充数据。由于我不知道如何在API中传递ID,因此我无法进行编辑。

代码:

Component.ts:

openModal(id : number, status : string): void {

const dialogRef = this.dialog.open(UpdateRowComponent, 
  {
    data :{
      'id' :id,
      'status': status } 

  });

dialogRef.afterClosed().subscribe((result:string) => {
   console.log('The dialog was closed');
  console.log(result);

});
}

Dialog.component.ts: (不使用服务)

  userId:string = "";
   id:number;
   Data:object = {};
 spf = [];
  exist = false;
  productObj:object = {};
  private headers = new Headers({ 'Content-Type': '  application/json'});
  @Input() item: any;

  constructor(private http: Http, public dialogRef :MatDialogRef<UpdateRowComponent >,private dialog: DialogService,private router:Router,private route:ActivatedRoute,
@Inject(MAT_DIALOG_DATA) public data: any) {
 console.log("Outside the subscriber",this.data);
 }

ngOnInit() {
  console.log("Inside update component",this.data);


  this.http.get("http://localhost:4000/Table/").subscribe(
    (res: Response) => {
      this.spf = res.json();
      for(var i = 0; i < this.spf.length ; i++) {
        if(parseInt(this.spf[i].id) === this.id) {
          this.exist = true;
          this.Data = this.spf[i];

          break;
        } else {
          this.exist = false;
        }
      }
    }
  )
}

这是我面临的问题(我无法在url中传递id,所以我应该在这里做什么?): dialog.component.ts:

    update(data) {
  this.productObj = {
    "status": data.status
  };
   const url = `${"http://localhost:4000/Table/"}/${this.id}`; 
  this.http.put(url, JSON.stringify(this.productObj), {headers: this.headers})
    .toPromise()
    .then(() => {
    console.log("Updated or ", this.data.status);
    })

}

2 个答案:

答案 0 :(得分:2)

尝试使用此

const url = `${"http://localhost:4000/Table/"}+"/"+${this.id}`; 

const url = "http://localhost:4000/Table/"+this.id; 

答案 1 :(得分:2)

首先,在这种情况下,您必须为URL参数指定一个名称,该名称可以为'id'。并尝试:

const url = "http://localhost:4000/Table?id="+this.id;

通过以下方式从组件中的URL获取ID

import { ActivatedRoute } from '@angular/router';
.
.
.
constructor(
    private route : ActivatedRoute,
) {}

ngOnInit() {
    var id : number;
    this.route.queryParams.subscribe( params => {
        id = params['id'];
    })
}