簡體   English   中英

使用AngularFire創建用戶並致電工廠以顯示通知

[英]Create User with AngularFire and call factory to display notifications

我是AngularJS的新手,並嘗試將其與AngularFire / Firebase結合使用以存儲一些項目數據。 我建立了一個工廠,該工廠應處理通知以將其顯示在中央位置。 工廠看起來像這樣:

myApp.factory("AlertService", function($timeout){
  var alerts = new Array();

  var addAlert = function(type, message){
    alerts.push({
      type: type,
      msg: message
    });
    $timeout(function(){
      removeAlert(alerts.length - 1);
    }, 3000);
  }

  var removeAlert = function(index){
    alerts.splice(index, 1);
  }

  return{
    alerts : alerts,
    addSuccessAlert : function(message){
      addAlert("success", message);
    },
    addDangerAlert : function(message){
      addAlert("danger", message);
    },
    deleteAlert : function(index){
      removeAlert(index);
    }
  };
});

在我使用$ watch的控制器中綁定數據

$scope.$watch( function () { return AlertService.alerts; }, function ( alerts ) {
  $scope.alerts = AlertService.alerts;
});

並將div放在index.html中:

<div id="alert">
  <alert ng-repeat="alert in alerts" type="{{alert.type}}">{{alert.msg}}</alert>
</div>

如果我調用AlertService.addWarningAlert("Your password is not identical");這將是完美的工作AlertService.addWarningAlert("Your password is not identical"); 從控制器內部。 但是,如果我現在嘗試在Firebase中創建用戶后顯示通知,則數據綁定不會更新(僅更新數組)。 那就是我創建用戶的方式:

var ref = new Firebase("https://xyz.firebaseio.com/"); 
ref.createUser({
  email    : $scope.data.suEmail,
  password : $scope.data.suPassword
}, function(error) {
  if (error === null) {
    console.log("User created successfully");
    AlertService.addSuccessAlert("User created successfully");
  } else {
    console.log("Error creating user:", error);
    AlertService.addWarningAlert("Error creating user");
  }
});

知道我做錯了嗎? 提前致謝!

編輯:這里Plnkr http://plnkr.co/edit/jSaJ5EzZ5MGRPFzhbGJg?p=preview

您僅使用Firebase JavaScript庫,而不使用AngularFire AngularFire建立在Firebase JS庫和Angular之上。 AngularFire做很多有用的事情,例如自動同步對象數組 (您可能需要檢查一下數組示例)。 AngularFire還可以正確處理$scope.apply 這樣,所有更新都將應用於視圖。

如果選擇不使用AngularFire,則需要在$timeout服務中包裝代碼的更新視圖的部分。

Plunker

  $scope.createUser = function(){
    ref.createUser({
        email    : "a.b@c.com",
        password : "mypassword"
      }, function(error) {

        // this will update the view because it's wrapped in $timeout
        $timeout(function() {
          if (error === null) {
            console.log("User created successfully");
            AlertService.addSuccessAlert("User created successfully");
          } else {
            console.log("Error creating user:", error);
            AlertService.addWarningAlert("Error while creating user");
          }
        });

      });
  }

我強烈建議對AngularFire文檔進行閱讀。 這將為您節省大量時間。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM