簡體   English   中英

EmberJS從ember-simple-auth身份驗證器檢索當前用戶

[英]EmberJS retrieve current user from ember-simple-auth authenticator

問題:

我正在嘗試通過擴展ember-simple-auth/authenticators/base來檢索從ember-simple-auth登錄的當前用戶。 我只想創建一個名為currentUser()的函數,該函數將返回用戶名,但是每當我嘗試調用該函數時,都會收到錯誤消息:

Uncaught TypeError: this.get(...).currentUser is not a function(…)

嘗試:

函數currentUser()定義如下:

// app/authenticators/oauth2.js
import Ember from 'ember';
import Base from 'ember-simple-auth/authenticators/base';

const RSVP = Ember.RSVP;

export default Base.extend({
  restore() {
      // restore user session
  },
  currentUser() {
      return this.get("username");
  }),
  authenticate(username, password) {
    this.set('username', username);
    return new RSVP.Promise((resolve, reject) => {
      Ember.$.ajax({
        url: config.baseURL + "accounts/login",
        data: {
          username: username,
          password: password
        },
        type: 'POST',
        dataType: 'json',
        contentType: 'application/x-www-form-urlencoded',
        complete: (response)=> {
          if (response.responseJSON.isAuthenticated)
            resolve({isAuthenticated: true});
          else
            reject("Wrong credentials.");
        }
      });
    });
  },
  invalidate() {
    // log out
  }
});

我使用以下函數調用了該函數:

// app/controllers/application.js
import Ember from 'ember';

export default Ember.Controller.extend({
  session: Ember.inject.service('session'),

  actions: {
    alertSession() {
      console.log("!! " + this.get('session').currentUser());
    },
    invalidateSession() {
      this.get('session').invalidate();
      this.transitionToRoute('login');
    }
  }
});

this.get('session').invalidate(); 可以,但是this.get('session').currentUser(); 將返回上述錯誤。 請讓我知道如何解決此問題。 另外,我正在使用Ember 2.5.1。

謝謝!

在您的應用程序控制器中,您正在從會話服務中調用currentUser() ,而您已經在oauth2.js身份驗證器中定義了currentUser() 執行可能會失敗,因為您尚未修改會話服務以引用對身份驗證器的currentUser函數的引用。

另一個函數成功執行,因為會話服務具有調用指定的驗證者的invalidate()函數所必需的引用。

您可以考慮使用ember-simple-auth的建議來管理當前用戶 這樣,您可以探索一種解決方案,該解決方案利用與會話服務結合使用的隔離currentUser服務。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM