gpt4 book ai didi

angularjs - RxJs 和 Angular1 组件 - 如何避免 $scope?

转载 作者:行者123 更新时间:2023-12-03 22:27:53 25 4
gpt4 key购买 nike

带有 RxJs 的 angular 1.5 组件的伪代码:

component('demo', {
template: `<div>
<div ng-if="verificationFailed">Sorry, failed to verify</div>
<button ng-if="continueEnabled">Continue</button>
<button ng-click="verify()">Verify</button>
</div>`,
controllerAs: 'ctrl',
bindings: {
someOptions: '='
},
controller: ($scope, someService) => {
var ctrl = this;

ctrl.continueEnabled = false;

ctrl.verificationFailed = false;

ctrl.verify = function() {
Rx
.Observable
.interval(10 * 1000)
.timeout(2 * 60 * 1000)
.flatMapLatest(_ => { someService.verify(ctrl.someOptions.id)})
.retry(1)
.filter((result) => { result.completed })
.take(1)
.subscribe(_ => {
$scope.$evalAsync(_ => {
ctrl.continueEnabled = true
});
}, _ => {
$scope.$evalAsync(() => {
ctrl.verificationFailed = true;
});
});
};
}
});

有什么方法可以避免将 $scope 与 $evalAsync 一起使用来触发摘要?没有它, View 根本不会更新。
为什么?因为 angular2 上没有 $scope 并且我想让迁移尽可能简单

最佳答案

您可以使用 angular1-async-filter。看看这篇好文章:
http://cvuorinen.net/2016/05/using-rxjs-observables-with-angularjs-1/

下面是一个例子:

(function(angular) {
var myComponent = (function () {
function myComponent() {
this.template = "<div><br/> Time: {{ctrl.time | async:this}}</div>";
this.controllerAs = 'ctrl';
this.controller = "myController";
}
return myComponent;
}());

var myController = (function() {
function myController() {
this.time = Rx.Observable.interval(1000).take(50);
}
return myController;
}());

angular.module('myApp', ['asyncFilter']);
angular.module('myApp').component('myComponent', new myComponent());
angular.module('myApp').controller('myController', myController);
})(window.angular);

看看它在 Plunker 上工作:
https://plnkr.co/edit/80S3AG?p=preview

关于angularjs - RxJs 和 Angular1 组件 - 如何避免 $scope?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36216172/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com