将id作为参数从URL传递到组件到Angular材质对话框

时间:2018-10-22 06:53:37

标签: angular

我正在尝试在Angular材质对话框中执行编辑操作。由于无法从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},
];

1 个答案:

答案 0 :(得分:0)

您的对话框组件中应包含以下内容:

Lizard

此数据可以在打开时传递给对话框(可以是任何东西)。因此,您可以(应该)使用它来传播您的ID,如下所示:

Reptile

它将在构造函数中以

的形式提供
 @Inject(MAT_DIALOG_DATA) public data: any