使用Typescript的角度材料吐司

时间:2015-11-02 13:03:55

标签: angularjs typescript angular-material

我是Typescript的新手,想要使用typescript显示Angular Material Dialog,但我无法配置Controller,因为typescript说“内容”不存在。哪个是对的,但我怎么说Typ​​escript它存在?

这是我的代码:

 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'
        })
    }

}

1 个答案:

答案 0 :(得分:1)

你应该先声明你的班级,即

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)"
        }
        //...
    });