Angular 2 Dependency注入不起作用

时间:2018-02-20 17:55:33

标签: angular dependency-injection

我正在写一个角度为2的应用程序,我想缓存一些数据。当你去每个页面时,我经常打电话给服务设计师而不是传递现有的对象。

  1. 组件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. 组件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();
        }
    }
    
  3. 服务

    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;
    }
    
  4. 每次导航时,控制台都会生成一个随机值,但在我看来,依赖注入应该缓存该值。可能是什么错误?

1 个答案:

答案 0 :(得分:0)

您的服务遗失@Injectable()

它应该是这样的:

@Injectable()
export class DataService
{ ... }