简体   繁体   中英

How to inject a service in a view component?

I have a layout component where I need to inject a service. but the service is undefined. Here's my code:

import {BaseLayout, LogEvent, Layout} from "ts-log-debug";
import {formatLogData} from "@tsed/common/node_modules/ts-log-debug/lib/layouts/utils/inspectUtils.js";
import { StorageService } from './StorageService';
import { IBasicLayoutConfiguration } from "@tsed/common/node_modules/ts-log-debug/lib/layouts/interfaces/BasicLayoutConfiguration";


@Layout({name: "customJson"})
export class JsonLayout extends BaseLayout {

  constructor(config : IBasicLayoutConfiguration , private storageService : StorageService) { 
    super(config);
  }

  transform(loggingEvent: LogEvent, timezoneOffset?): string {
      const log = {

           Id:{ Id: () => {
                       return this.storageService && this.storageService.getId() || '';
                  },
                },

          context: context
      };
      log.data = log.data.map((data) => formatLogData([data]));
      return JSON.stringify(log) + (this.config["separator"] || "");
  };

}

I have the service in the providers array in the app.module.ts file. what am I doing wrong?

If you have a service,that needs to be injected into the angular component:

1) create a service, that is annotated with @Injectable(), like below

@Injectable()
export class StudyService

2) you have to inject that in the component constructor like you are already doing with StorageService:

 constructor(private studyService: StudyService){}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM