我想知道如何从位于" parent"中的路由器插座标签中显示的组件传递数据。组件HTML模板到这个父组件?
答案 0 :(得分:0)
首先,您需要在顶部创建父组件。在该父组件中,您需要在需要的地方注入服务。
服务应该像:import { Component, Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
@Injectable()
export class HeaderService {
private headerSource: BehaviorSubject<boolean> = new BehaviorSubject(false);
header = this.headerSource.asObservable();
changeMode(mode) {
this.headerSource.next(mode);
}
}
并在您的父组件中:
import {Component, OnInit} from "@angular/core";
import { Subscription } from 'rxjs/Subscription';
import { HeaderService } from "../HeaderService";
@Component({
selector: "App",
template: `<navbar *ngIf="userMode"></navbar>
<router-outlet></router-outlet>
`
})
export class AppComponent {
userMode: boolean = false;
subscription: Subscription;
constructor(private headerService: HeaderService) {
this.subscription = this.headerService.header
.subscribe(mode => this.userMode = mode);
}
}
现在你可以改变路由器插座内子组件的模式,如下所示:
import { Component} from '@angular/core';
import { HeaderService } from "../HeaderService";
@Component({
selector: "child",
templateUrl: "app/components/home.html"
})
export class HomeComponent{
constructor(private headerService: HeaderService) {
this.headerService.changeMode(true);
})
}
希望这对您的情况有所帮助。 Gud Luck!