EmberJS——載入/錯誤子狀態



Ember.js 透過利用錯誤和載入子狀態,重寫了路由之間的非同步定製轉換。

語法

Ember.Route.extend ({
   model() {
      //code here
   }
});

Router.map(function() {
   this.route('path1', function() {
      this.route('path2');
   });
});

示例

下面給出的示例演示了在載入路由時發生的載入/錯誤子狀態的使用。建立一個新路由並將其命名為 loaderror,並使用以下程式碼開啟 router.js 檔案,以定義 URL 對映 -

import Ember from 'ember';                   
//Access to Ember.js library as variable Ember
import config from './config/environment';
//It provides access to app's configuration data as variable config 

//The const declares read only variable
const Router = Ember.Router.extend ({
   location: config.locationType,
   rootURL: config.rootURL
});

//Defines URL mappings that takes parameter as an object to create the routes
Router.map(function() {
   this.route('loaderror', function() {
      this.route('loaderr');
   });
});

//It specifies Router variable available to other parts of the app
export default Router; 

開啟在 app/routes/ 下建立的檔案loaderror.js ,程式碼如下 -

import Ember from 'ember';

export default Ember.Route.extend ({
   model() {
      return new Ember.RSVP.Promise(function (resolve, reject) {
         setTimeout(function () {
            resolve({});
         }, 1500);
      });
   }
});

開啟在 app/templates/ 下建立的檔案 application.hbs ,程式碼如下 -

{{outlet}}

開啟檔案 index.hbs 並新增以下程式碼 -

{{link-to 'loaderror' 'loaderror'}} 
<small>(this link displays the 'loading' route/template correctly)</small>
{{outlet}}

當您單擊 loaderror 連結時,頁面應在正在載入的狀態下開啟。因此,建立一個 Loading.hbs 檔案來指定正在載入的狀態 -

<h2 style = "color: #f00;">template: loading</h2>

現在開啟顯示錯誤訊息的檔案 loaderror.hbs -

<h2>--error--!</h2>
{{link-to 'loaderror.loaderr' 'loaderror.loaderr'}} 
<small>(doesn't display the 'loading' route/template, 
   because 'loaderror/loading' does not exist!!!</small>
{{outlet}}

輸出

執行 ember 伺服器,您將收到以下輸出 -

Ember.js Router Load Error Substates

當您單擊連結時,它將顯示模板載入訊息 -

Ember.js Router Load Error Substates

然後,當在轉換期間遇到錯誤時,它會顯示一個錯誤子狀態 -

Ember.js Router Load Error Substates
emberjs_router.htm
廣告
© . All rights reserved.