从角度服务返回空值的变量

Variable returning null from Angular Service?

本文关键字:空值 变量 返回 服务      更新时间:2023-09-26

我有一个使用 AngularJS 构建的 SharePoint 应用程序。我有一个控制器正在调用服务中的函数,但它没有返回值。我对angularJS很陌生,所以我有点迷茫。我的服务:

App.factory('uploadAppService', function () {
return {
    currentUserPic: function (myProfileProp) { 
        GetUserProfileInfo(myProfileProp).done(function (data) {
            //The large thumbnail pic.
            var picUrl = data.d.PictureUrl;
            var largePicUrl = picUrl.replace('MThumb', 'LThumb');
            console.log(largePicUrl) //the log here is correct. I want to return the largePicUrl back to my controller.
            return largePicUrl;
        });
    }

我的控制器调用,我想用服务中的 url 填充.imageUrl

$scope.imageUrl = uploadAppService.currentUserPic("PictureUrl");

提前谢谢你。

对我来说

,你的currentUserPic函数似乎没有返回值。 GetUserProfileInfo确实返回了您的 largePicUrl,但此值不会在任何地方使用(如果我正确理解您的代码)。

你不应该使用return GetUserProfileInfo(myProfileProp).done(...);吗?

编辑:但正如RaviH指出的那样,如果调用是异步的,您仍然必须在控制器中处理它。

我没有看到您的GetUserProfileInfo服务的实现,但我想它是一个 Deffered 对象。

所以在代码之后

$scope.imageUrl = uploadAppService.currentUserPic("PictureUrl");

完成工作 - 变量$scope.imageUrl中没有任何内容,因为工厂函数不返回任何内容。

因此,首先您需要修改factory

App.factory('uploadAppService', function () {
return {
    currentUserPic: function (myProfileProp) { 
        return GetUserProfileInfo(myProfileProp).done(function (data) {
        // ^
        // Here - @ababashka's edit
            //The large thumbnail pic.
            var picUrl = data.d.PictureUrl;
            var largePicUrl = picUrl.replace('MThumb', 'LThumb');
            console.log(largePicUrl) //the log here is correct. I want to return the largePicUrl back to my controller.
            return largePicUrl;
        });
    }

返回 Deffered 对象,因此在它完成工作后,您可以通过在 response 中获取图像 URL 来保存图像 URL。

在需要编写下一个代码之后:

uploadAppService.currentUserPic("PictureUrl").done(
  function (response) {
    $scope.imageUrl = response;
  }
);

将您的 URL 存储在 $scope 的变量中。