首页 > 解决方案 > 我们可以在子组件中访问父组件更改的服务数据吗

问题描述

路由:

children: [
      {
        path: "",
        component: parentcomponent,
        children: [
          {
            path: "welcome",
            component: childcomponent
          }]

在父组件中:我有路由器插座来加载子组件

<router-outlet> </router-outlet>

this.service.current="0"; 我正在从父组件设置服务中的数据并尝试从子组件访问相同但无法在子组件中查看服务的任何属性

在子组件中,无法访问父组件更改的服务值

标签: angular

解决方案


我会使用实际的“服务”在组件之间共享状态和数据。我有一个简短的指南,您可以在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也有一个随附的代码仓库。

希望这可以帮助!如果没有,请如前所述发布您的其余代码。-马修


推荐阅读