Angular 2 中的更改检测

Change detection in Angular 2

我正在将 angular 1 和 angular 2 整合在一起。因此我有 angular 1 个控制器和服务以及 angular 2 个组件。这些对于数据检索和存储都很好,反之亦然。下面是我的 html 页面。

<body>
<h3>Angular 1 service</h3>
<div ng-controller="MainController">
    <input ng-model="username" />
    <button ng-click="setUser()">Set User</button>
    <button ng-click="getUser()">Get User</button>
    <div>User in service : {{user}}</div>
</div>
<hr>
<h3>Angular 2 component uses Angular 1 service</h3>
<user-section></user-section>
</body>

控制器如下,

myApp.controller('MainController', function ($scope, UserService) {
    $scope.getUsers = function () {
        UserService.setUser($scope.username);
        window.location = './angular2.html'
    };

    $scope.setUser = function () {
        UserService.setUser($scope.username);
        $scope.user = $scope.username;
    };

    $scope.getUser = function () {
        $scope.user = UserService.getUser();
    };
});

服务如下,

function UserService(){
    this.user = "default";
}

UserService.prototype.getUsers = function(){
    var users = ['user1', 'user2', 'user3'];
    return users;
}

UserService.prototype.setUser = function(usr){
    this.user = usr;
}

UserService.prototype.getUser = function(){
    return this.user;
}

angular2个分量如下,

    import {Component, Inject} from 'angular2/core';

    @Component({
        selector: 'user-section',
        templateUrl: '<div>
                      <input [(ngModel)]="username" />
                      <button (click)="setUser()">Set User</button>
                      <button (click)="getUser()">Get User</button>
                      <button (click)="getUsers()">Get Users</button>
                      <br/>
                      <ul>
                       <li *ngFor="#userId of users">{{userId}}</li>
                      </ul>
                      <div>User in service : {{user}}</div>
                      </div>'
   })
 export class UserSection {
        constructor(@Inject('UserService') userService:UserService) {
                this.users = [];
                this.username = '';
                this._UserService = userService;    
            }

        getUsers(){
            this.users = this._UserService.getUsers();
        }

        setUser(){
            this._UserService.setUser(this.username);
        }

        getUser(){
            this.user = this._UserService.getUser();
        }
    }

需要始终为 angular 2 触发事件(getUser)以从 angular 1 中获取名称。工作 plunker https://plnkr.co/edit/fYbIeJUUY7Xst7GEoi2v?p=preview 每当 angular 1 输入更改时,我想更新 angular 2 模型。有没有办法做到这一点? angular 2 中有监听器,但我不知道如何让他们监听 angular 1 服务。

我猜你应该看看 Angular2 中的 ngDoCheckOnChanges 生命周期挂钩以及 Angular1 中的 $apply。

使用 $apply 你的控制器修改如下

var myApp = angular.module("hybridExampleApp", []);

//define as Angular 1 service
myApp.service('UserService', UserService);

myApp.controller('MainController', function ($scope, UserService) {

   $scope.$watch('username',function(){
        $scope.setUser();
     });
    $scope.getUsers = function () {
        UserService.setUser($scope.username);
        window.location = './angular2.html'
    };

    $scope.setUser = function () {
        UserService.setUser($scope.username);
        $scope.user = $scope.username;
    };

    $scope.getUser = function () {
        $scope.user = UserService.getUser();
    };
});

使用 ngDoCheck 你的 user.section.component.ts 修改如下

import {Component, Inject,ChangeDetectionStrategy,ngDoCheck,ngOnChanges} from 'angular2/core';

@Component({
    selector: 'user-section',
    templateUrl: './src/ng2-component/user.section.tpl.html',
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class UserSection implements ngDoCheck, ngOnChanges{

  username123:number;

constructor(@Inject('UserService') userService:UserService) {
        this.users = [];
        this.username = '';

        this.user=0;
        this._UserService = userService;
    }
    ngOnChanges(){
      console.log('adfkjna');

    }

    getUsers():void{
        this.users = this._UserService.getUsers();
    } 

    setUser():void{
        this._UserService.setUser(this.username);
    }

    getUser():void{ 
        this.user = this._UserService.getUser();
    }
     ngDoCheck(){

    this.user = this._UserService.getUser();
     this.getUser();
    console.log(this.user);

    }
}

我的代码完全记录 angular 1 中的用户名更改,但我不明白为什么它没有将它绑定到 UI.

LIVE DEMO 你更新的 plunker。