【问题标题】:Service doesn't print console.log服务不打印 console.log
【发布时间】:2020-05-15 19:40:39
【问题描述】:

我需要在我的 Angular 应用程序中创建一个服务,所以我这样做:

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

  products: string[] = [];

  constructor(private http: HttpClient) {
    console.log('HI');
    this.http.get('****').subscribe(data => {
    //   console.log(data);
   });
  }
}

在我的 app.module 中我这样做:

import {PropertiesNameService} from './propertiesName/properties-name.service';
....

providers: [PropertiesNameService],

问题是,当我启动应用程序并打开控制台时,我看不到 "HI" 。我使用 Angular 8 有人可以帮助我吗?

【问题讨论】:

  • 您在哪里使用过这项服务?或者更好的是,你在哪里注入了这个服务?
  • 由于您使用的是 Injectable 的 providedIn: 'root' 功能,因此您不必将其显式添加到 AppModule 中的 providers 数组中。 ng build --aot --prod 是否输出任何错误?
  • 现在该服务没用了,但我尝试以这种方式查看它的应用程序会打印我的 console.log

标签: angular angular8 angular-services


【解决方案1】:

到目前为止,似乎没有人真正使用该服务。有一个带有constructor (private propertiesNameService: PropertiesNameService) {} 的组件,它将实例化服务并运行其构造函数。

【讨论】:

  • 不,我需要使用此服务,但如果它有效,我将不理会“console.log”
  • 有没有注入PropertiesNameService的组件?可以是AppComponent,也可以是其他任何一个。
【解决方案2】:

providedIn: 'root' 指定 Angular 应该在根注入器中提供服务。

所以:

服务:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http'
@Injectable({
  providedIn: 'root'
})
export class ServiceService {

  constructor(private http: HttpClient) {

  }

  onHttp(){
    return   console.log('Message from service');
    // return this.http.get('****')
  }

}

还有你的 app.component:

constructor(private service: ServiceService) { <---instantiate the service

 }

 onClick(){
   this.service.onHttp()
 }

 ngOnInit(){
   this.onClick()
 }

https://stackblitz.com/edit/angular-heiywb?file=src%2Fapp%2Fapp.component.ts

希望对你有帮助!

【讨论】:

    猜你喜欢
    • 2019-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-12
    • 1970-01-01
    • 2018-06-30
    • 2012-12-30
    相关资源
    最近更新 更多