我正在尝试在角度材质对话框中执行编辑操作。我无法执行编辑操作,因为我无法从 URL 获取参数。如何将 id 作为参数从当前组件传递到 Dialog 组件?
Component.ts:
openModal(id : number): void {
const dialogRef = this.dialog.open(UpdateRowComponent, {
});
dialogRef.afterClosed().subscribe((result:string) => {
this.router.navigate(['UpdateRowComponent',id]);
console.log('The dialog was closed');
console.log(result);
});
}
UpdateRowComponent.ts(对话框(:未使用的服务。直接在组件内部执行操作
import { Component, OnInit, Inject } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
import { Http,Response,Headers } from "@angular/http";
import { ActivatedRoute, Router } from '@angular/router';
@Component({
selector: 'app-update-row',
templateUrl: './update-row.component.html',
styleUrls: ['./update-row.component.css']
})
export class UpdateRowComponent implements OnInit {
userId:string = "";
id:number;
Data:object = {};
spf = [];
exist = false;
productObj:object = {};
private headers = new Headers({ 'Content-Type': 'application/json'});
constructor(private http: Http, public dialogRef :MatDialogRef<UpdateRowComponent >,private dialog: DialogService,private router:Router,private route:ActivatedRoute,
@Inject(MAT_DIALOG_DATA) public data: any) { }
ngOnInit() {
this.route.params.subscribe(params => {
this.id = +params['id'];
});
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;
}
}
}
)
}
update(user) {
this.productObj = {
"Status": user.status
};
const url = `${"http://localhost:4000/Table/"}/${this.id}`;
this.http.put(url, JSON.stringify(this.productObj), {headers: this.headers})
.toPromise()
.then(() => {
this.router.navigate(['/dashboard']);
})
}
}
路线:
import import { UpdateRowComponent } from './update-row/update-row.component';
import { CurrentComponent } from './update-row/update-row.component';
const appRoutes: Routes = [
{path: 'currentComp',component: CurrentComponent},
{path: 'update/:id',component: UpdateRowComponent},
];
对话框组件中应该有这样的东西:
@Inject(MAT_DIALOG_DATA) public data: any
打开对话框时,可以将此数据传递(并且可以是任何内容(。所以你可以使用它(你应该(像这样传播你的 Id:
const dialogRef = this.dialog.open(UpdateRowComponent, {
data:{myId:myIdValue}
});
它将在构造函数中作为
this.data.myId //==myIdValue