[英]Can we access service data changed by parent component in child component
路由:
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 上還有一個隨附的代碼存儲庫。
希望這可以幫助! 如果沒有,請發布之前提到的其余代碼。 -馬修
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.