在非嵌套组件之间传输数据

时间:2016-10-24 13:10:20

标签: angularjs angular typescript angularjs-directive angularjs-scope

基本上,我想要的是传输数据黑白组件。

我在母版页上有一个angular2组件,用于登录的部分视图 -

<loginpartial></loginpartial>

最初通过此html模板使用子组件 -

进行渲染
<ul [hidden]="!item.isAuthenticated">
    <li><a href="javascript:;">Hello! {{item.userName}}</a></li>
    <li><a href="javascript:;">LogOff</a></li>
</ul>
<ul [hidden]="item.isAuthenticated">
    <li><a href="javascript:;">Hello! User</a></li>
    <li><a href="javascript:;">Log In</a></li>
</ul>

子组件 -

@Component({
    selector: 'loginpartial',
    templateUrl: '../Templates/LoginPartial.html'
})

export class LoginPartialComponent implements OnInit {
    public item: any = { isAuthenticated: false, userName: ' ' }
    constructor() {
        this.item.isAuthenticated = false;
    }

    ngOnInit() {
        this.item.isAuthenticated = false;
    }
}

我希望到现在为止这是有道理的。现在,只要用户登录,我的需求是什么,我想从父组件传输的部分视图中获取用户名。

父组件

import { Component, ChangeDetectionStrategy, OnInit} from '@angular/core';
import {LoginPartialComponent} from '../loginpartialview/loginpartial.component.ts';
import {SharedService} from '../sharedService/app.sharedService.ts';

@Component({
    selector: 'loginmodel',
    templateUrl: '../Templates/Login.html',
    changeDetection: ChangeDetectionStrategy.OnPush,
    providers: [LoginPartialComponent,SharedService]
})
export class LoginComponent implements OnInit {
    item: any = {
        isAuthenticated: false, userName: ' '
    };
    constructor(private sharedService: SharedService,
        private loginComp: LoginPartialComponent) {
    }

    onSubmit(item: any): void {
        if (this.myForm.valid) {
            var userObject = {
                email: item.email,
                password: item.password
            };
            this.sharedService.getLogin(userObject).map(response => response.json())
                .subscribe(
                data => this.handleResult(data),
                error => console.log(error)
                );
        }
    }

    private handleResult(data) {
        if (data.success) {
            this.item.isAuthenticated = true;
            this.item.userName = data.userName;
            this.item = this.loginComp.item;
        }
        else {

        }
    }
}

正如您在父组件中看到的那样,当调用onSubmit函数时,我的登录表单提交时,我正在调用handleResult来设置来自ajax调用的数据共享服务。

这不会让子组件 - LoginPartialComponent刷新。我尝试使用@Input()类型参数,但没有帮助我。

更新 -

正如@Camaron在他的回答中所说,我只为事件发射器创建了一个依赖于此登录目的。但这不起作用。

LoginPartialComponent

import { Component, OnInit} from '@angular/core';
import {LoginPartialModel} from '../loginpartialview/loginpartial.model.ts';
import {SharedService} from '../sharedService/app.sharedService.ts';

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

@Component({
    selector: 'loginpartial',
    templateUrl: '../Templates/LoginPartial.html',
    providers: [SharedService]
})

export class LoginPartialComponent {
    item: LoginPartialModel = new LoginPartialModel();
    constructor(private service: SharedService) {
        this.service.onLoginSuccess.subscribe((loginData: any) => this.item == loginData.item);
    }

}

LoginComponent

import { Component, OnInit} from '@angular/core';
import {SharedService} from '../sharedService/app.sharedService.ts';

@Component({
    selector: 'loginmodel',
    templateUrl: '../Templates/Login.html',
    providers: [SharedService]
})
export class LoginComponent {

    constructor(private sharedService: SharedService) {
    }

    onSubmit(item: any): void {
            var userObject = {
                email: item.email,
                password: item.password
            };
            this.sharedService.getLogin(userObject).map(response => response.json())
                .subscribe(
                data => this.handleResult(data),
                error => console.log(error)
                );
    }
    private handleResult(data) {
        if (data.success) {
            this.close();
            this.sharedService.onLoginSuccess.emit(data);
        }
        else {

        }
    }
}

共享服务(依赖关系)

import { Component, Injectable, EventEmitter} from '@angular/core';

@Injectable()
export class SharedService {

    onLoginSuccess: EventEmitter<any> = new EventEmitter<any>();
    constructor() {
    }

    notifyLoginSuccess(item: any): void {
        this.onLoginSuccess.emit({ item: item });
    }
}

这不起作用。

2 个答案:

答案 0 :(得分:1)

尝试使用服务来建立subscribe LoginPartialComponent。{/ p>

@Injectable()
export class LoginService {

    onLoginSuccess: EventEmitter<any>() = new EventEmitter<any>();

    constructor() {
    }

    notifyLoginSuccess(item:any):void {
        this.onLoginSuccess.emit({item: item});
    }

}

然后在两个组件上注入此服务。 在LoginPartialComponent订阅此服务活动。

constructor(public loginService:LoginService) {
    this.loginService.onLoginSuccess.subscribe((loginData: any) => this.item = loginData.item);
}

然后在handleResult函数中拨打loginService.notifyLoginSuccess并发送item

使用此解决方案,您可以删除组件的依赖关系,以便 LoginComponent 不需要知道 LoginPartialComponent

答案 1 :(得分:1)

我认为首选的Angular-fanatic方式是在一个组件中创建一个函数(或者我认为服务,虽然我猜它现在只是组件的一部分)可观察并订阅它。

我认为这篇文章很好地说明了这一点:

http://mean.expert/2016/05/21/angular-2-component-communication/

还要注意父级的输入和输出属性 - &gt;孩子,反之亦然。

相关问题