Change detection in Angular 2

前端 未结 1 1615
不知归路
不知归路 2021-01-26 00:57

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 stor

相关标签:
1条回答
  • 2021-01-26 01:30

    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.

    0 讨论(0)
提交回复
热议问题