在我的主控制器中,我有一个返回当前用户的用户服务。
// Curr user
userService.getCurrentUser().then(user => {
mainCtrl.currUser = user;
});
有没有办法在不注入我的服务的情况下在其他控制器中使用currUser
变量并在50个控制器中反复调用此方法?
实施例
// My other awesome controller
console.log(currUser.fullName);
答案 0 :(得分:1)
如果您确定不使用提供商/服务,您可以选择 LocalStorage
或$rootScope.
<强>示例:强>
public async Task<Stream> GetApproveDocumentAsync<T>(Guid id, int revision, PdfLayoutType pdfLayoutType, string resourceFilePath, CadDrawingType cadDrawingType, int approvalWidth, int approvalHeight, Action<T> fillModelAction = null) where T : BaseApproveModel, new() {
var previewFileName = $"{id}_{revision}_preview.png";
Stream previewFile;
using (var resourceFileStream = new FileStream(resourceFilePath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, true)) {
previewFile = await _cadApiService.ConvertDrawingToImageAsync(resourceFileStream, cadDrawingType, FileFormat.EVD, FileFormat.PNG, approvalWidth, approvalHeight).ConfigureAwait(false);
}
Func<string[], T> createBaseApproveModelFunc = graphicContentFilenames => { //Implicitly captured closure: previewFile
var model = new T {
GraphicContentFiles = graphicContentFilenames,
CadPreview = previewFileName,
Customer = _userService.GetCurrentOverrideCustomer()?.CustomerName
};
fillModelAction?.Invoke(model);
return model;
};
Action<List<StreamWithFileName>> fillGraphicContentAction = currentGraphicContent => { //Implicitly captured closure: fillModelAction, this
currentGraphicContent.Add(new StreamWithFileName {FileName = previewFileName, Stream = previewFile});
};
return await _apagoService.ConstcutPdf(pdfLayoutType, createBaseApproveModelFunc, fillGraphicContentAction).ConfigureAwait(false);
}
然后将其作为,
访问myApp.controller('DemoController1', ['$scope', '$rootScope', function DemoController($scope,$rootScope) {
$rootScope.currUser.fullName ="test";
}]);
答案 1 :(得分:0)
您可以使用$rootScope
,如下所示:
mainCtrl.$rootScope.currUser = user;
和另一个控制器,你可以恢复如下:
console.log(yourContrl.$rootScope.currUser.fullName);
答案 2 :(得分:0)
您不希望使用控制器注射吗?使用injector
就像注射一样,但也不同:D ...就像在runnable fiddle demo中一样。通过这种方式,您仍然可以使用服务,工厂或组件。
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function ($scope) {
$scope.name = angular.injector(['data']).get('user').currUser.username;
});
angular.module('data', []).factory('user', function () {
return {
currUser: {
username: 'Alfred'
}
}
});