为什么不能将user_name值传递到组件中? (验证)

时间:2019-01-31 15:25:05

标签: vue.js vuejs2

我正在尝试将身份验证后的用户名传递给Vue组件,但加载后会得到一个name: undefined值。

  

这是我的AuthService.js

//config details taken from OAUTH JS doc: https://github.com/andreassolberg/jso

import { JSO, Fetcher } from 'jso';

const client = new JSO({
  providerID: '<my-provider>',
  default_lifetime: 1800,
  client_id: '<my-client-id>',
  redirect_uri: 'http://localhost:8080/',
  authorization:'<my-auth-server>/oauth/authorize'
  //scopes: { request: ['https://www.googleapis.com/auth/userinfo.profile'] }
});

export default {
  getProfile() {
    // JSO plugin provides a simple wrapper around the fetch API to handle headers
    let f = new Fetcher(client);
    let url = 'https://www.googleapis.com/auth/userinfo.profile';
    f.fetch(url, {})
      .then(data => {
        return data.json();
      })
      .then(data => {
        return data.user_name;
      })
      .catch(err => {
        console.error('Error from fetcher', err);
      });
  }
};
  

然后,在名为MainNav的单个文件组件中,我具有:

import AuthService from "@/AuthService";
export default {
  name: "MainNav",
  data() {
    return {
      name: ""
    };
  },
  created() {
    this.name = AuthService.getProfile();
  }
};
</script>

关于如何从AuthService到组件中获取user_name值的任何提示?然后,我需要在导航模板中显示名称。进行console.log测试工作正常,只是无法将其返回给我的SFC。 此外,JSO库在这里:https://github.com/andreassolberg/jso#fetching-data-from-a-oauth-protected-endpoint

1 个答案:

答案 0 :(得分:0)

因为getProfile不返回任何内容(未定义)。我看到您使用es6,然后可以使用异步功能

//config details taken from OAUTH JS doc: https://github.com/andreassolberg/jso

import { JSO, Fetcher } from 'jso';

const client = new JSO({
  providerID: '<my-provider>',
  default_lifetime: 1800,
  client_id: '<my-client-id>',
  redirect_uri: 'http://localhost:8080/',
  authorization:'<my-auth-server>/oauth/authorize'
  //scopes: { request: ['https://www.googleapis.com/auth/userinfo.profile'] }
});

export default {
  getProfile() {
  // JSO plugin provides a simple wrapper around the fetch API to handle headers
  let f = new Fetcher(client);
  let url = 'https://www.googleapis.com/auth/userinfo.profile';
  return f.fetch(url, {}) // return promise here
    .then(data => {
      return data.json();
    })
    .then(data => {
      return data.user_name;
    })
    .catch(err => {
      console.error('Error from fetcher', err);
    });
  }
};

import AuthService from "@/AuthService";
export default {
  name: "MainNav",
  data() {
    return {
      name: ""
    };
  },
  async created() {
    try {
      this.name = await AuthService.getProfile();
    } catch(error) {
      // handle
    }
  }
};
</script>

或者没有异步(然后再添加一个)

import AuthService from "@/AuthService";
export default {
  name: "MainNav",
  data() {
    return {
      name: ""
    };
  },
  created() {
    AuthService.getProfile().then((userName) => this.name = userName))
      .catch((error) => { /* handle */ })
  }
};
</script>