getters: { token: (state) => {return state.keycloak?.token},…
- User
getters: { token: (state) => {return state.keycloak?.token}, username:(state)=>state.keycloak?.tokenParsed?.preferred_username, email:(state)=>state.keycloak?.tokenParsed?.email }这个有什么问题
- Assistant
这个getter函数没有明显的问题。它返回state对象中keycloak属性的token、username和email。然而,需要确保在使用这个getter函数之前,确保已经正确初始化和设置了state对象中的keycloak属性。否则,这些属性可能不存在或为null,导致获取不到相应的值。
- User
getters: (state) =>{ token: (state) => {return state.keycloak?.token}, username:(state)=>state.keycloak?.tokenParsed?.preferred_username, email:(state)=>state.keycloak?.tokenParsed?.email },这样写有问题嘛
- Assistant
是的,这样写是有问题的。你的getter函数应该是一个对象,而不是一个函数。正确的写法应该是以下形式:
getters: { token: (state) => {return state.keycloak?.token}, username: (state) => state.keycloak?.tokenParsed?.preferred_username, email: (state) => state.keycloak?.tokenParsed?.email }这样就可以正确定义并访问这些getter函数了。注意在获取token、username和email的时候,你可以省略不必要的括号,并使用可选链操作符(?)来处理可能为null或未定义的情况。
- User
async initializeKeycloak() { const my_promise = new Promise((resolve, reject) => { const keycloak = new Keycloak({ url: "http://192.168.1.8:8080/", realm: "sinno", clientId: "sinno_pd_manager", }); keycloak.init({ onLoad: "login-required", checkLoginIframe: false, // otherwise it would reload the window every so seconds enableLogging: true, pkceMethod: 'S256', flow: 'standard', }).then((authenticated) => { if (authenticated) { //将 Promise 的状态由"未完成"改为"成功" this.keycloak = keycloak //把注册的keycloak存到store里 resolve(
首次登录,Keycloak授权成功!\nToken:\n${this.keycloak.token}) } else { //将 Promise 的状态由"未完成"改为"失败", reject(new Error(Keycloak授权失败!${authenticated})) } }) //上面在调用keycloak.init后根据状态设定了promise的最终状态,下面同理,根据promise的状态进行下一步处理 }).then((success_msg) => { console.log(success_msg) //添加定时器 this.createRefreshTokenTimer(this.keycloak); }).catch((error) => { console.error("首次登录,Keycloak授权失败!", error) window.location.reload() }) },如何去掉promise - Assistant
要去掉Promise,可以使用async/await语法来重写代码。这样可以让代码更清晰、更易读。以下是使用async/await重写的代码示例:
async initializeKeycloak() { try { const keycloak = new Keycloak({ url: "http://192.168.1.8:8080/", realm: "sinno", clientId: "sinno_pd_manager", }); const authenticated = await keycloak.init({ onLoad: "login-required", checkLoginIframe: false, enableLogging: true, pkceMethod: 'S256', flow: 'standard', }); if (authenticated) { this.keycloak = keycloak; console.log(`首次登录,Keycloak授权成功!\nToken:\n${this.keycloak.token}`); this.createRefreshTokenTimer(this.keycloak); } else { throw new Error(`Keycloak授权失败!${authenticated}`); } } catch (error) { console.error("首次登录,Keycloak授权失败!", error); window.location.reload(); } }使用async/await语法,你可以直接使用await关键字在异步操作完成后接收结果。通过使用try/catch语句块,你可以捕获和处理错误。这种方式使得代码结构更加清晰,并且避免了过多的嵌套和使用Promise的复杂性。