将数据从子组件传递到父组件 [英] Passing Data From Child Component Into Parent Component

查看:102
本文介绍了将数据从子组件传递到父组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的角度有问题,这里有两个组成部分:

I have problems with my angular, here I have two components:


  • MyApp(ParentComponent)

  • LoginPage(ChildComponent)

我有一个属性 UserNow 的部分 MyApp 我想通过组件 LoginPage设置属性 UserNow 的值。怎么做?

I have a property UserNow in parts MyApp and I want to set the value of the property UserNow through the components LoginPage. How to do it?

我试过(但没有给出任何影响)

I have tried (but did not give any influence)

Import {MyApp} from '../../app/app.component'; 

@Component({
  selector: 'page-login',
  templateUrl: 'login.html'
})
export class LoginPage {
    public app: any;

    login() {
        ...
        this.app = MyApp;
        this.app.userNow = MyValue;
        ...
    }
}


推荐答案

有几种方法可以做到。

1)使用服务:服务通常在应用程序中有一个实例,可用于轻松共享组件之间的数据。
例如创建一个服务userService并将其注入您想要使用它的组件中。

1) Using a service: A service generally has a single instance in the application and can be used to share data between the components easily. E.g. create a service userService and inject it in components where ever you want to use it.

2)使用Emit:Emit用于在应用程序中发出事件并执行相应的操作可以采取。

2) using Emit: Emit is used to emit an event in the application and corresponding action can be taken.

this.eventInChild.emit(data);

可以对事件发生采取两项措施。

Two actions can be taken on event emission.


  • 调用父母的函数:

< child-component (eventInChild)=parentFunction($ event)>< / child-component>


  • 发光从服务和订阅活动(可以在服务和组件中订阅):

在服务中它是这样的:

getEmitStatus() {
    return this.eventInService;
}

//In component or service - to listen to event

this.subscription = this.userService.getEmitStatus()
    .subscribe(item => {
         //thing to do here
}); 

这篇关于将数据从子组件传递到父组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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