gpt4 book ai didi

angular - 如何在 Angular2 中将变量值从一个组件传递到另一个组件

转载 作者:太空狗 更新时间:2023-10-29 18:16:04 24 4
gpt4 key购买 nike

我正在使用 Angular4 和 angular-cli 重建一个旧的网络平台(用 php 编码)。

我正在寻找一种在名为 my-configuration 的组件中一次声明多个变量的方法,以便我可以直接在其他组件(例如 my-footer)中使用它们,而无需重新声明它们:

我的配置.component.ts

import {Component} from '@angular/core';

@Component ({
selector: 'my-configuration',
templateUrl: './my-configuration.component.html',
styleUrls: ['./my-configuration.component.css']
})

export class MyConfigurationComponent {
variable1: String;
variable2: String;

constructor(){
this.variable1 = 'value1';
this.variable2 = 'value2';
}
}

我的页脚.component.ts

import {Component} from '@angular/core';

@Component ({
selector: 'my-footer',
templateUrl: './my-footer.component.html',
styleUrls: ['./my-footer.component.css']
})

export class MyFooterComponent {
footer-variable1: String;
footer-variable2: String;

constructor(){
this.footer-variable1 = //Get the variable1 value from MyConfigurationComponent;
this.footer-variable1 = //Get the variable2 value from MyConfigurationComponent;
}
}

这样做的正确方法是什么?

最佳答案

在整个应用程序中共享数据的推荐方法是使用 Angular 服务。它们被定义为单例,因此您保留在那里的任何值都可用于整个应用程序。

您可以在此处找到有关服务的更多信息:https://angular.io/docs/ts/latest/tutorial/toh-pt4.html

我只是整理了一篇博文和一个 plunker 来展示如何做到这一点:

http://blogs.msmvps.com/deborahk/build-a-simple-angular-service-to-share-data/

enter code here

https://plnkr.co/edit/KT4JLmpcwGBM2xdZQeI9?p=preview

关于angular - 如何在 Angular2 中将变量值从一个组件传递到另一个组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43809529/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com