Angular 共享给各种服务和组件的变量
Angular variable shared to various services and components
我有几个组件和服务定义了从各个组件调用的函数。现在我想添加一个可以在主 app.component 中使用标签设置但可以从任何地方访问的变量。你能建议如何完成这个吗?
app.component.html
<h1>{{title}}</h1>
<nav>
<a routerLink="/dashboard">Dashboard</a>
<a routerLink="/comp1">Comp1</a>
<a routerLink="/comp2">Comp2</a>
<select class="form-control" id="selectedValue"
[(ngModel)]="selectedValue">
<option value="1">1</option>
<option value="2">2</option>
</select>
</nav>
<p>Selected value is {{selectedValue}}</p>
<router-outlet></router-outlet>
<app-messages></app-messages>
类似这样,但我不想在 app.component.ts 中定义变量,而是在其他地方定义,比如在“common/shared”服务中。
然后我会在各种服务中使用这个变量,例如
https://whosebug.com/posts/${selectedValue}
首先,有时使用全局变量意味着您没有正确的代码设计,这可能不是您的情况。
无论如何, 到另一个 post 可能就是您要找的。
如果您认为您的问题可以通过其他方式解决,请随时添加更多信息,说明您尝试使用代码实现的目标。
我有几个组件和服务定义了从各个组件调用的函数。现在我想添加一个可以在主 app.component 中使用标签设置但可以从任何地方访问的变量。你能建议如何完成这个吗?
app.component.html
<h1>{{title}}</h1>
<nav>
<a routerLink="/dashboard">Dashboard</a>
<a routerLink="/comp1">Comp1</a>
<a routerLink="/comp2">Comp2</a>
<select class="form-control" id="selectedValue"
[(ngModel)]="selectedValue">
<option value="1">1</option>
<option value="2">2</option>
</select>
</nav>
<p>Selected value is {{selectedValue}}</p>
<router-outlet></router-outlet>
<app-messages></app-messages>
类似这样,但我不想在 app.component.ts 中定义变量,而是在其他地方定义,比如在“common/shared”服务中。
然后我会在各种服务中使用这个变量,例如
https://whosebug.com/posts/${selectedValue}
首先,有时使用全局变量意味着您没有正确的代码设计,这可能不是您的情况。
无论如何,
如果您认为您的问题可以通过其他方式解决,请随时添加更多信息,说明您尝试使用代码实现的目标。