enter code here有效的方法是使用 Cloud Functions for Firebase(Google Cloud Functions 的一部分),在用户登录时触发,运行 Node 发送 HTTP 请求以获取令牌,然后将结果写入 AngularJS 值服务。
此云功能有效:
// Node modules
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const request = require('request'); // node module to send HTTP requests
const fs = require('fs');
admin.initializeApp(functions.config().firebase);
exports.getWatsonToken = functions.database.ref('userLoginEvent').onUpdate(event => { // authentication trigger when user logs in
var username = 'groucho',
password = 'swordfish',
url = 'https://' + username + ':' + password + '@stream.watsonplatform.net/authorization/api/v1/token?url=https://stream.watsonplatform.net/speech-to-text/api';
request({url: url}, function (error, response, body) {
var tokenService = "app.value('watsonToken','" + body + "');";
fs.writeFile('../public/javascript/services/watsonTokenValue.js', tokenService, (err) => {
if (err) throw err;
console.log('The file has been saved!');
}); // close fs.writeFile
}); // close request
}); // close getWatsonToken
在控制器中:
firebase.auth().onAuthStateChanged(function(user) { // this runs on login
if (user) { // user is signed in
console.log("User signed in!");
$scope.authData = user;
firebase.database().ref('userLoginEvent').update({'user': user.uid}); // update Firebase database to trigger Cloud Function to get a new IBM Watson token
} // end if user is signed in
else { // User is signed out
console.log("User signed out.");
}
}); // end onAuthStateChanged
遍历Cloud Function,它注入了四个Node模块,包括request用于发送HTTP请求,fs用于将结果写入文件。然后将触发器设置为更新到 Firebase 数据库(我从控制台创建)中的位置 userLoginEvent。接下来,HTTP 请求发出。响应(令牌)称为body。 app.value('watsonToken','" + body + "');" 是包装令牌的 Angular 值服务。然后fs 将所有这些写入我项目中的某个位置。
在 AngularJS 控制器中,onAuthStateChanged 在用户登录时触发。然后将 user.uid 更新为 Firebase 数据库中的位置 userLoginEvent,Cloud Function 触发,HTTP 请求发出,然后响应被写入 Angular 服务。