如何在角度4中使用mdDialogref进行正常路由?

时间:2017-05-03 05:55:42

标签: angular routing dialog

import { Component, NgModule } from '@angular/core';
import { MdDialog } from '@angular/material';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { Product } from '../../models';
import { ProductService } from '../../services/product.service';
import { MdDialogRef } from '@angular/material';
@Component({
    selector: 'product',
    template: `
    <button mdButton class="md-fab md-primary md-hue-2 addProduct" aria-label="Profile" (click)="openDialog()" >
        add
    </button>
    `
})
export class ProductComponent {
    constructor(public dialog: MdDialog, public dialogRef: MdDialogRef<AddProductComponent>) { }
    openDialog() {
        this.dialogRef = this.dialog.open(AddProductComponent);
    }
}

@Component({
    selector: 'addproduct',
    template: require('./add.product.html'),
})
export class AddProductComponent {
    constructor(public productService: ProductService, public dialogRef: MdDialogRef<AddProductComponent>) {
    }



    addProduct(product: Product) {
        this.productService.addProduct(product).subscribe(() => {
            this.dialogRef.close();
            //this.productService.getAllProducts();
        });
    }
}

这对我来说很完美,但是当我在logincomponent

中使用时
this.router.navigate(['/product']);

它引发了我

的错误

错误错误:未捕获(承诺):错误:没有MdDialogRef的提供者!

当我在stackoverflow上讨论这个问题时:

"No provider for MdDialogRef!"

that tells that we should not use component by <product></product>.But I need to call product component when I get success of login.So How do I do normal routing with mdDialogRef ?

1 个答案:

答案 0 :(得分:1)

我尝试使用 MdDialogRef componentInstance 属性。效果很好:

import { Component, NgModule } from '@angular/core';
import { MdDialog } from '@angular/material';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { Product } from '../../models';
import { ProductService } from '../../services/product.service';
import { MdDialogRef } from '@angular/material';
@Component({
    selector: 'product',
    template: `
    <button mdButton class="md-fab md-primary md-hue-2 addProduct" aria-label="Profile" (click)="openDialog()" >
        add
    </button>
    `
})
export class ProductComponent {
    constructor(public dialog: MdDialog) { }
    openDialog() {
        let dialogRef = this.dialog.open(AddProductComponent);

        //Set the dialogRef property of opened dialog with the obtained ref
        dialogRef.componentInstance.dialogRef = dialogRef;
    }
}

@Component({
    selector: 'addproduct',
    template: require('./add.product.html'),
})
export class AddProductComponent {
    public dialogRef:<any> = null; 
    constructor(public productService: ProductService) {
    }



    addProduct(product: Product) {
        this.productService.addProduct(product).subscribe(() => {
            this.dialogRef.close();
            //this.productService.getAllProducts();
        });
    }
}