当前位置: 首页 > 文档资料 > EmberJS 入门教程 >

路由器暂停承诺(The Router Pauses for Promises)

优质
小牛编辑
128浏览
2023-12-01

可以通过从模型钩子返回promise来暂停转换。 通过从模型返回普通对象或数组,可以立即完成转换。

语法 (Syntax)

Ember.Route.extend ({
   model() {
      return new Ember.RSVP.Promise(function(param) {
         //code here
      });
   }
});

例子 (Example)

下面给出的示例显示了如果模型返回承诺,转换将如何暂停。 创建一个新路由并将其命名为promisepause并打开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('promisepause');
});
//It specifies Router variable available to other parts of the app
export default Router;

使用以下代码打开在app/templates/下创建的application.hbs文件 -

<h2>Router Pauses for Promises</h2>
{{#link-to 'promisepause'}}Click Here{{/link-to}}

单击上面的链接时,将打开“承诺暂停模板”页面。 promisepause.hbs文件包含以下代码 -

{{model.msg}}
{{outlet}}

现在使用以下代码打开在app/routes/下创建的promisepause.js文件 -

import Ember from 'ember';
import RSVP from 'rsvp';
export default Ember.Route.extend ({
   model() {
      //RSVP.js is an implementation of Promises
      return new Ember.RSVP.Promise(function (resolve) {
         Ember.run.later(function () {
            //display the promise message
            resolve ({
               msg: "This is Promise Message..."
            });
         }, 3000); //time in milli second to display promise
      });
   }
});

输出 (Output)

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

Ember.js暂停承诺

当您单击链接时,模型将返回在3秒之前未解决的承诺,并且当承诺履行时,路由器将开始转换 -

Ember.js暂停承诺