angularjs firebase 用户身份验证服务未与视图通信

编程入门 行业动态 更新时间:2024-10-27 01:27:10
本文介绍了angularjs firebase 用户身份验证服务未与视图通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我有一个将参数 pseudonym 传递给环境的服务.我在我的视图中调用了这个化名,但它根本没有出现.
如何解决此问题以在我的视图中显示值?

I have a service which passes on the parameter pseudonym to the evironment. I call on this pseudonym in my views, but it doesn't appear at all.
How can I fix this to display the value in my views?

MyUser 服务:

app.service('MyUser', ['DatabaseRef', 'firebase', function(DatabaseRef, firebase) {
    var pseudonym ="";
    var userId = firebase.auth().currentUser.uid;

    return {
        pseudonym: function() {
            DatabaseRef.ref('/users/' + userId).once('value')
                .then(function (snapshot) {
                    pseudonym = snapshot.val().pseudonym;
                    console.log("pseudony: ", pseudonym);
                    return pseudonym;
                });

        }
    }
}]);

在我的控制台中,我看到了 pseudonym 的值.但在我看来,html 使用 {{pseudonym}}
这是示例视图控制器:

in my console, I see the value for the pseudonym. but not in my view html using {{pseudonym}}
and here is the example view controller:

app.controller('ExampleCtrl', ["MyUser",
    function (MyUser) {
     $scope.pseudonym = MyUser.pseudonym();
}]);

推荐答案

返回.then方法创建的promise:

Return the promise created by the .then method:

app.service('MyUser', ['DatabaseRef', 'firebase', function(DatabaseRef, firebase) {
    //var pseudonym ="";
    var userId = firebase.auth().currentUser.uid;

    return {
        getUserName: function() {
            //return promise
            return (
                DatabaseRef.ref('/users/' + userId).once('value')
                    .then(function onSuccess(snapshot) {
                        let pseudonym = snapshot.val().pseudonym;
                        console.log("pseudony: ", pseudonym);
                        return pseudonym;
                })
            );
        }
    }
}]);

然后从该承诺中提取值:

Then extract the value from that promise:

var app = angular.module('app', []);
app.controller('loginController',['$scope', 'MyUser',function($scope, MyUser)
{
    let promise = MyUser.getUserName();
    //Extract data from promise
    promise.then( function onSuccess(pseudonym) {
        $scope.pseudonym  = pseudonym;
        console.log($scope.pseudonym);
    });
}]);

对象的 .then 方法总是返回一个从处理函数返回的值(或承诺)派生的承诺,作为该 .then 方法的参数提供.

The .then method of an object always returns a promise derived from the value (or promise) returned by the handler function furnished as an argument to that .then method.

这篇关于angularjs firebase 用户身份验证服务未与视图通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-21 14:49:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1004387.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:视图   身份验证   通信   用户   angularjs

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!