在使用Angular中的route.navigate
进行路由时,父组件中注入的服务不会自动传递给子组件。这是因为路由导航会销毁当前组件并创建一个新的组件实例,而不是简单地切换组件的视图。
要在父组件中注入的服务能够在子组件中使用,可以通过以下几种方式实现:
@Input
装饰器:在父组件中将服务实例作为属性传递给子组件,并使用@Input
装饰器将其标记为输入属性。子组件可以通过这个输入属性来访问父组件中的服务实例。父组件:
import { Component } from '@angular/core';
import { MyService } from './my.service';
@Component({
selector: 'app-parent',
template: `
<app-child [myService]="myService"></app-child>
`,
providers: [MyService]
})
export class ParentComponent {
myService: MyService;
constructor() {
this.myService = new MyService();
}
}
子组件:
import { Component, Input } from '@angular/core';
import { MyService } from './my.service';
@Component({
selector: 'app-child',
template: `
<p>{{ myService.getData() }}</p>
`
})
export class ChildComponent {
@Input() myService: MyService;
}
@ViewChild
装饰器:在父组件中使用@ViewChild
装饰器获取子组件的实例,并手动将父组件中的服务实例赋值给子组件。父组件:
import { Component, ViewChild } from '@angular/core';
import { MyService } from './my.service';
import { ChildComponent } from './child.component';
@Component({
selector: 'app-parent',
template: `
<app-child></app-child>
`,
providers: [MyService]
})
export class ParentComponent {
@ViewChild(ChildComponent) childComponent: ChildComponent;
myService: MyService;
constructor() {
this.myService = new MyService();
}
ngAfterViewInit() {
this.childComponent.myService = this.myService;
}
}
子组件:
import { Component } from '@angular/core';
import { MyService } from './my.service';
@Component({
selector: 'app-child',
template: `
<p>{{ myService.getData() }}</p>
`
})
export class ChildComponent {
myService: MyService;
}
共享服务:
import { Injectable } from '@angular/core';
@Injectable()
export class SharedService {
data: any;
setData(data: any) {
this.data = data;
}
getData() {
return this.data;
}
}
父组件:
import { Component } from '@angular/core';
import { SharedService } from './shared.service';
@Component({
selector: 'app-parent',
template: `
<button (click)="setData()">Set Data</button>
<app-child></app-child>
`,
providers: [SharedService]
})
export class ParentComponent {
constructor(private sharedService: SharedService) {}
setData() {
this.sharedService.setData('Hello from parent');
}
}
子组件:
import { Component } from '@angular/core';
import { SharedService } from './shared.service';
@Component({
selector: 'app-child',
template: `
<p>{{ sharedService.getData() }}</p>
`
})
export class ChildComponent {
constructor(public sharedService: SharedService) {}
}
这些方法可以根据具体的需求选择使用,以实现在父组件中注入的服务能够在子组件中使用。
领取专属 10元无门槛券
手把手带您无忧上云