Angular material 使用 Typescript toast

Angular material toast using Typescript

我是 Typescript 的新手,想用 typescript 显示 Angular Material 对话框,但我无法配置控制器,因为 typescript 说 "content" 不存在。哪个是对的,但我怎么说 Typescript 存在呢?

这是我的代码:

 interface IToastService {
    displayError(text: string): void;
    displaySuccess(text: string): void;
}

export class ToastService implements IToastService {
    public static $inject = ['$mdToast'];
    constructor(
        private $mdToast: angular.material.IToastService) { }

    displayError(text: string): void {
        this.$mdToast.show({
            position: 'top left',
            controller: () => {
                this.content = text; // the Error Line
            },            
            controllerAs: 'toast',
            template: '<md-toast>\
                        {{ toast.content }}\
                        <md-button ng-click="toast.cancel()" class="md-warn">\
                                 <md-icon md-font-set="material-icons"> clear </md-icon>\
                    </md-button>\
                </md-toast>',
            hideDelay: 0
        });
    }

    displaySuccess(text: string): void {

        this.$mdToast.show({

            template: '<md-toast>\
                        {{ toast.content }}\
                           <md-icon md-font-set="material-icons" style="color:#259b24"> done </md-icon>\
                </md-toast>',
            hideDelay: 1000,
            position: 'top left',
            controller: () => {
                this.content = text;
            },
            controllerAs: 'toast'
        })
    }

}

您应该预先将其声明为您的 class,即

export class ToastService implements IToastService {
   public content:string; //Here

   public static $inject = ['$mdToast'];
//...

但您似乎在使用箭头运算符。这意味着 属性 content 不会附加到模态的控制器实例,而是附加到 ToastService 实例(当模态控制器被实例化时)。我相信您需要将其声明为正常功能。

this.$mdToast.show({
        position: 'top left',
        controller: function() {
            this.content = text; //Now this is your controller instance
        },            
        controllerAs: 'toast',
        //...
    });

您还应该能够将参数 text 作为 toast 的解析传递并接受它作为控制器的参数。即

    this.$mdToast.show({
        position: 'top left',
        controller: function(content:string) {
            this.content = content; 
            //If you define this as class, you could do "private content:string"
        },            
        controllerAs: 'toast',
        resolve:{
           content: () => text
           //Not sure if it is very specific only about a promise, if so you
           //would need to inject $q and do "content: ()=> $q.when(test)"
        }
        //...
    });