[英]Angular 2 Dependency injection does not work
我在angular 2上编写了一个应用程序,我想缓存一些数据。 当您转到每个页面时,我会不断地致电服务设计人员,而不是传递现有对象。
组件1:
import { Component, OnInit } from '@angular/core'; import { DataService } from '../services/globaldata.service' import { User } from '../models/User'; @Component({ selector: 'Campaigns', templateUrl: './campaigns.component.html', providers: [DataService] }) export class CampaignComponent implements OnInit { public user: User; constructor(private dataService: DataService) { this.user = dataService.getData(); } ngOnInit() { this.user = this.dataService.getData(); } }
组件2:
import { Component, OnInit } from '@angular/core'; import { DataService } from '../services/globaldata.service' import { User } from '../models/User'; @Component({ selector: 'Wallet', templateUrl: './wallet.component.html', providers: [DataService] }) export class WalletComponent implements OnInit { public user: User; constructor(private dataService: DataService) { this.user = dataService.getData(); } ngOnInit() { this.user = this.dataService.getData(); } }
服务:
import { User } from '../models/user'; export class DataService { private data: User; getData(): User { return this.data; } setData( price: number) { this.data = new User(price); } constructor() { this.data = new User(this.randomInteger(1,1000)); } public randomInteger(min:number, max:number) { var rand = min - 0.5 + Math.random() * (max - min + 1) rand = Math.round(rand); console.log(rand); return rand; }
控制台每次导航时都会生成一个随机值,但是我认为依赖项注入应该缓存该值。 可能是什么错误?
您的服务缺少@Injectable()
:
它看起来应该像这样:
@Injectable()
export class DataService
{ ... }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.