目录

Loading/Error Substates

Ember.js通过使用错误和加载子状态来覆盖转换以自定义路由之间的异步。

语法 (Syntax)

Ember.Route.extend ({
   model() {
      //code here
   }
});
Router.map(function() {
   this.route('path1', function() {
      this.route('path2');
   });
});

例子 (Example)

下面给出的示例演示了在加载路径时使用的加载/错误子状态。 创建一个新路由并将其命名为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}}

输出 (Output)

运行ember服务器,您将收到以下输出 -

Ember.js路由器加载错误子状态

当您单击该链接时,它将显示模板加载消息 -

Ember.js路由器加载错误子状态

然后在转换期间遇到错误时显示错误子状态 -

Ember.js路由器加载错误子状态
↑回到顶部↑
WIKI教程 @2018