将数据从子组件传递到父组件 [英] Passing Data From Child Component Into Parent Component
问题描述
我的角度有问题,这里有两个组件:
I have problems with my angular, here I have two components:
- MyApp(父组件)
- 登录页面(子组件)
我在 MyApp
部分有一个属性 UserNow
,我想通过组件 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) using 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屋!