为什么我的角度服务变量未定义?

我一直在尝试从代码中的一个组件到另一个组件获取变量,但是它返回未定义的

我的服务

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

@Injectable({
  providedIn: 'root'
})
export class ColorService {

  public color : string;

  constructor() { }
}

我的应用程序模块

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';

import { RouterModule, Routes } from '@angular/router';

import { ColorService } from './core/color.service';

import { UserComponent } from './user/user.component';
import { PublicComponent } from './public/public.component';

const routes : Routes = [
  {
    path: '',
    redirectTo: 'user',
    pathMatch: 'full'
  },
  {
    path: 'user',
    component: UserComponent
  },
  {
    path: 'public',
    component: PublicComponent
  },
  {
    path: '**',
    redirectTo: 'user'
  }
]

@NgModule({
  declarations: [
    AppComponent,
    UserComponent,
    PublicComponent
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(routes)
  ],
  providers: [
    ColorService
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

我的用户组件

import { Component, OnInit } from '@angular/core';
import { ColorService } from '../core/color.service';

@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.scss']
})
export class UserComponent implements OnInit {

  constructor(private color: ColorService) { }

  ngOnInit(): void {

  }

  colorit(){
    this.color.color = 'blue';
    console.log(this.color.color);
  }

}

以及应该获取颜色字符串的组件

import { Component, OnInit } from '@angular/core';
import { ColorService } from '../core/color.service';

@Component({
  selector: 'app-public',
  templateUrl: './public.component.html',
  styleUrls: ['./public.component.scss']
})
export class PublicComponent implements OnInit {

  constructor(private color: ColorService) { }

  ngOnInit(): void {

  }

  getColor(){
    console.log(this.color.color);
  }
}

但是,每次我尝试在公共组件中获取颜色时,我都会得到一个未定义的颜色,即使它包含在appModule的提供程序中

评论