通过服务将数据传递到“路由器出口”子组件中

时间:2018-07-26 07:57:46

标签: rxjs angular6

我通过服务将数据传递到“ router-outlet”子组件中,但没有任何作用。

app.service.ts

import { Injectable } from '@angular/core';
import { Subject }    from 'rxjs';

@Injectable()
export class AppService {

  private themeAnnouncedSource = new Subject<string>();

  themeAnnounced$ = this.themeAnnouncedSource.asObservable();

  getTheme(theme: string) {
    this.themeAnnouncedSource.next(theme);
  }
}

app.component.ts

import { Component} from '@angular/core';
import { AppService }     from './app.service';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss'],
    providers: [AppService]
})
export class AppComponent {
    theme: string = 'theme-three';

    constructor(private appService: AppService) {}

    ngOnInit() {
        this.appService.getTheme(this.theme);
    }
}

index.component.ts

import { Component, Input, OnDestroy} from '@angular/core';
import { AppService } from '../../app.service';
import { Subscription }   from 'rxjs';

@Component({
    selector: 'app-index',
    templateUrl: './index.component.html',
    styleUrls: ['./index.component.scss'],
})
export class IndexComponent implements OnDestroy {
    themeType: string;
    subscription: Subscription;
    constructor(private appService: AppService) {
        this.subscription = this.appService.themeAnnounced$.subscribe(
            theme => this.themeType = theme); 
    }

    ngOnInit() { 
        this.themeType    // undefined
    }
    ngOnDestroy() {
        // prevent memory leak when component destroyed
        this.subscription.unsubscribe();
    }
}

我想将app.component的主题变量的值传递到index.component的路由器子组件中,但是它不起作用。我无法获得主题变量的价值。

0 个答案:

没有答案