在非嵌套组件之间传输数据 [英] Transferring data between non-nested components

查看:62
本文介绍了在非嵌套组件之间传输数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Basically , What I desire is to transfer data b/w components.

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

I have one angular2 component on master page for partial view of login -

<loginpartial></loginpartial>

这最初是通过带有子组件-

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

我希望到现在为止这都是有意义的.现在,我需要的是,一旦用户登录,我想在此局部视图中从父组件转移来获取用户名.

I hope this makes sense till now. Now What my need is as soon as user is logged in , I want to get username in this partial view transferred from parent component.

父组件

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调用中的数据.

As you can see from this parent component when onSubmit function is called which is my login form submission I am calling handleResult that is setting data from ajax call from the shared service.

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

This is not letting the child component - LoginPartialComponent refresh. I tried with @Input() type parameters too but didn't help me.

更新-

正如@Camaron在他的回答中所说,我为此登录目的创建的依赖项仅与事件发射器有关.但这是行不通的.

As @Camaron said in his answer I created a dependency for this login purpose only with event emitters. But this doesn't work.

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

这行不通.

推荐答案

尝试使用服务建立此通信subscribe LoginPartialComponent.

Try to use a service to establish this communication subscribe the LoginPartialComponent.

@Injectable()
export class LoginService {

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

    constructor() {
    }

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

}

然后在两个组件上注入此服务. 在您的LoginPartialComponent中订阅此服务事件.

And then Inject this service on both components. In your LoginPartialComponent subscribe to this service event.

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

然后在您的handleResult函数中调用loginService.notifyLoginSuccess并发送item.

Then in your handleResult function make a call to loginService.notifyLoginSuccess and send the item.

使用此解决方案,您可以删除组件的依赖性,因此 LoginComponent 不需要知道存在 LoginPartialComponent .

With this solution you can remove the dependency of your components so the LoginComponent don't need to know that there is a LoginPartialComponent.

这篇关于在非嵌套组件之间传输数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆