我对角度很新,并试图弄清楚如何让组件功能相互通信。
我有一个phone-list.component.js,我在其中执行依赖于会话变量的HTTP get:
angular.
module('phoneList').
component('phoneList', {
templateUrl: '/phone-list.template.html',
controller: ['$http',
function PhoneListController($http) {
var self = this;
var access_token = '';
var data = $.param({
grant_type: 'password',
username: 'test',
password: 'test',
client_id:'1234',
client_secret:'12345',
});
var config = {
headers : {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
}
}
$http.post('/o/token/', data, config)
.success(function (data, status, headers, config) {
self.access_token = data['access_token'];
console.log(access_token);
})
.error(function (data, status, header, config) {
$scope.ResponseDetails = "Data: " + data +
"<hr />status: " + status +
"<hr />headers: " + header +
"<hr />config: " + config;
});
var header = {
headers : {
'Authorization': 'Bearer '+self.access_token
}
}
$http({method: 'GET', url: 'api/posts/', headers: {'Authorization': 'Bearer '+self.access_token}}).then(function(response) {
self.phones = response.data;
});
}
]
});
我在名为authentication.component.js的文件中生成另一个模块中的变量:
angular.module('authentication').factory('authenticationService', function($http, $se){
function authenticate(){
$http.post('/o/token/', data, config)
.success(function (data, status, headers, config) {
console.log('auth service: '+data['access_token']);
$sessionStorage.access_token = data['access_token'];
});
}
function getToken(){
return $sessionStorage.access_token;
}
return {
authenticate:authenticate,
getToken:getToken
};
});
我的app.module.js看起来像这样:
angular.module('phonecatApp', [
'ngRoute',
'phoneList',
'authentication',
]);
我的phone-list.module.js如下所示:
angular.module('phonecatApp', [
// ...which depends on the `phoneList` module
'phoneList',
'authentication',
]);
angular.module('phoneList', []);