EmberJS - 加载/错误子状态
Ember.js 通过使用错误和加载子状态覆盖转换以自定义路由之间的异步。
语法
Ember.Route.extend ({ model() { //代码在这里 } }); Router.map(function() { this.route('path1', function() { this.route('path2'); }); });
示例
下面给出的示例演示了在加载路由时出现的"正在加载/错误"子状态的使用。创建一个新路由并将其命名为 loaderror,然后使用以下代码打开 router.js 文件来定义 URL 映射 −
import Ember from 'ember'; //以变量 Ember 的形式访问 Ember.js 库 import config from './config/environment'; //它以变量 config 的形式提供对应用程序配置数据的访问 //const 声明只读变量 const Router = Ember.Router.extend ({ location: config.locationType, rootURL: config.rootURL }); //定义以参数为对象来创建路由的 URL 映射 Router.map(function() { this.route('loaderror', function() { this.route('loaderr'); }); }); //它指定可供应用程序其他部分使用的 Router 变量 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 状态打开。因此,创建一个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 服务器,您将收到以下输出 −
单击链接时,将显示模板加载消息 −
然后,在转换期间遇到错误时,它会显示错误子状态 −