Tag:koa2ejs
Article From:https://segmentfault.com/q/1010000012151880
Question:
admin.get('/usermsg', async(ctx) => {    
    var count = await new Promise(function(resolve, reject){
        User.count(function(err, count){
            if(count){
                resolve(count);
            }

            if(err){
                reject(err);
            }
        });
    })

    ctx.state.userMsg = {
        page: Number(ctx.query.page),        //Page numberLimit: 4, / / the number of users displayed per pagePages: 0,/ / total number of pagesCount: count / / user information quantity}Var userMsg = ctx.statE.userMsg;Ctx.state.users = await new Promise (function (resolve, reject) {UserMsg.pages= Math.ceil (userMsg.count / userMsg.limit);UserMsg.page = userMsg.page > userMsg.pagesUserMsg.pages: userMsg.page; //page can't be greater than pages, not less than 1.UserMsg.page = userMsg.page &lT; 1? 1: userMsg.page;Var skip = (userMsg.page - 1) * userMsg.limit; / /Each page starts reading from the number of user informationUser.find ().Limit (userMsg.limit).Skip (skip).Exec (function (err, DOC) {If (DOC) {Resolve (DOC);}If (ERR) {RejeCT (ERR);}})})Await ctx.render ('admin/usermsg');})

In the above route, ctx.state.userMsg can be passed to the template. This data is also needed in the next routing. How should I pass it to him?

admin.get('/category', async(ctx) => {
    await ctx.render('admin/category');
})

Answer 0:

await next()And chain operation

For example:

// controllers/test.js
async function get (ctx, next) {
    const res = await models.test.get()
    
    ctx.state.code = 0
    ctx.state.data = res.data
    
    await next()
}
module.exports = get
import controllers from '../controllers/test'

admin.get('/category', controllers.test, async(ctx) => {
    await ctx.render('admin/category', {
        list: ctx.state.data
    });
})

Similar Posts:

Leave a Reply

Your email address will not be published. Required fields are marked *