2015-11-02 66 views
2

我是Typescript的新手,想用打字稿顯示Angular Material對話框,但我無法配置控制器,因爲打字稿說「內容」不存在。哪個是對的,但是我怎麼說Typ​​escript它存在?使用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' 
     }) 
    } 

} 

回答

0

你應該只把它聲明類的前期,即

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爲土司的決心和接受它作爲控制器的參數。即

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

雖然我不明白你的第二個例子,第一個例子對我很好。謝謝! – EffGee

+0

嗨,你能幫我在[這](http://stackoverflow.com/q/33997547/4044949) –