Change detection in Angular 2

2019-03-06 12:33发布

问题:

I am integrating angular 1 and angular 2 together. Therefore I have angular 1 controller and service and angular 2 component. Those are working fine for data retrieving and storing vice versa. Below is my html page.

<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>

The controller is as below,

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();
    };
});

The service is as below,

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;
}

The angular 2 component is as below,

    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();
        }
    }

An event(getUser) needs to be fired always for angular 2 to get the name from the angular 1. Working plunker https://plnkr.co/edit/fYbIeJUUY7Xst7GEoi2v?p=preview I want to update the angular 2 model whenever the angular 1 input is changed. Is there a way to do this? There are listeners in angular 2, but I don't know how to make them listen to angular 1 service.

回答1:

I guess you should have a look at the ngDoCheck and OnChanges lifecycle hooks in Angular2 and $apply in your Angular1.

using $apply your controller is modified as below

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();
    };
});

Using ngDoCheck your user.section.component.ts is modified as below

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);

    }
}

My code is completely logging the username changes in angular 1, but I can't figure why is it not binding it to the UI.

LIVE DEMO of your updated plunker.