angular - 我们可以在子组件中访问父组件更改的服务数据吗
问题描述
路由:
children: [
{
path: "",
component: parentcomponent,
children: [
{
path: "welcome",
component: childcomponent
}]
在父组件中:我有路由器插座来加载子组件
<router-outlet> </router-outlet>
this.service.current="0";
我正在从父组件设置服务中的数据并尝试从子组件访问相同但无法在子组件中查看服务的任何属性
在子组件中,无法访问父组件更改的服务值
解决方案
我会使用实际的“服务”在组件之间共享状态和数据。我有一个简短的指南,您可以在https://matthewdavis.io/theme-service查看。
这是一个例子:
服务:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class ThemeService {
/**
* Variable to hold our setting.
*/
public darkMode: boolean;
/**
* Enable/disable "dark mode" by flipping the bit.
*/
public toggle(): void {
this.darkMode = !this.darkMode;
}
}
应用组件:
import { Component } from '@angular/core';
import { ThemeService } from './theme.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: [ './app.component.scss' ]
})
export class AppComponent {
/**
* Inject the theme service which will be called by our button (click).
*
* @param {ThemeService} themeService instance.
*/
public constructor(public themeService: ThemeService) {
}
}
在视图中使用服务:
<div class="wrapper" [class.dark-mode]="themeService.darkMode">
<div class="text">
Dark Mode Enabled? {{ themeService.darkMode ? 'YES' : 'NO' }}
</div>
<div class="button">
Parent Component
<button (click)="themeService.toggle()">Toggle!</button>
</div>
<app-child></app-child>
</div>
本指南在https://github.com/mateothegreat/ng-byexamples-theme-service也有一个随附的代码仓库。
希望这可以帮助!如果没有,请如前所述发布您的其余代码。-马修
推荐阅读
- python - 使用列表时在赋值错误之前使用变量
- python - 我无法使用 BeautifulSoup 从表中提取数据
- java - 我的程序陷入了不应执行的循环
- c++ - (MSVC 2017 /WALL & /WX) 包括 Iostream 产生 800 个警告
- ruby-on-rails - 如何将来自不同模型的多个对象合并为 Rails 中的一个对象?
- javascript - 如何以编程方式仅选择用户可选择的所有文本节点
- git - 如何以交互方式将块(差异块)分配给一组新提交?
- ios - 我的 ViewController 中的每个 textField 输入是否都必须有 textField.delegate=self
- python - 如何将函数定义为包入口点?
- python - 如何保存在一段代码中创建的列表,以便在再次使用相同代码时可以再次使用它?