Angular 2

时间:2017-01-11 06:47:33

标签: angularjs angular typescript integration

我将角度1和角度2集成在一起。因此我有角度1控制器和服务和角度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;
}

角度2分量如下,

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

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

1 个答案:

答案 0 :(得分:1)

我想你应该看看Angular2中的 ngDoCheck OnChanges 生命周期钩子以及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);

    }
}

我的代码完全记录用户名在角度1中更改,但我无法理解为什么它不会将其绑定到 UI

LIVE DEMO 您更新的plunker。