标签: angular2-di

Angular DI错误 - EXCEPTION:无法解析所有参数

我在Angular中构建了一个基本的应用程序,但是我遇到了一个奇怪的问题,我不能将服务注入到我的一个组件中.它注入了我创建的其他三个组件中的任何一个.

首先,这是服务:

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

@Injectable()
export class MobileService {
  screenWidth: number;
  screenHeight: number;

  constructor() {
    this.screenWidth = window.outerWidth;
    this.screenHeight = window.outerHeight;

    window.addEventListener("resize", this.onWindowResize.bind(this) )
  }

  onWindowResize(ev: Event) {
    var win = (ev.currentTarget as Window);
    this.screenWidth = win.outerWidth;
    this.screenHeight = win.outerHeight;
  }

}
Run Code Online (Sandbox Code Playgroud)

它拒绝使用的组件:

import { Component, } from '@angular/core';
import { NgClass } from '@angular/common';
import { ROUTER_DIRECTIVES } from '@angular/router';

import {MobileService} from '../';

@Component({
  moduleId: module.id,
  selector: 'pm-header',
  templateUrl: 'header.component.html',
  styleUrls: ['header.component.css'],
  directives: [ROUTER_DIRECTIVES, …
Run Code Online (Sandbox Code Playgroud)

angular2-di angular

389
推荐指数
16
解决办法
30万
查看次数

获取没有构造函数注入的服务实例

@Injectable在bootstrap中定义了一个服务.我想在不使用构造函数注入的情况下获取服务的实例.我试过使用ReflectiveInjector.resolveAndCreate但似乎创建了一个新实例.

我试图做的原因是我有一个由许多组件派生的基本组件.现在我需要访问服务,但我不想将它添加到ctor,因为我不想在所有衍生组件上注入服务.

TLDR:我需要一个 ServiceLocator.GetInstance<T>()

更新: RC5 +的更新代码:存储用于组件的进样器实例

angular2-injection angular2-di angular

59
推荐指数
4
解决办法
5万
查看次数

如何将父组件注入子组件?

我正在尝试将父组件注入子组件.我认为这很简单 - 只需在子代中指定/注入父组件constructor():

constructor(private _parent:AppComponent) {}   // child component constructor
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

EXCEPTION:无法解析ChildComponent(?)的所有参数.确保它们都具有有效的类型或注释.

我错过了什么?

ChildComponent:

import {Component} from 'angular2/core';
import {AppComponent} from './app.component';

@Component({
  selector: 'child',
  template: `<p>child</p>`
})
export class ChildComponent {
  constructor(private _parent:AppComponent) {}
}
Run Code Online (Sandbox Code Playgroud)

AppComponent:

import {Component} from 'angular2/core';
import {ChildComponent} from './child.component';

@Component({
  selector: 'my-app',
  template: `{{title}} <child></child>
  `,
  directives: [ChildComponent]
})
export class AppComponent {
  title = "Angular 2 - inject parent";
  constructor() { console.clear(); }
}
Run Code Online (Sandbox Code Playgroud)

Plunker

angular2-di angular

37
推荐指数
2
解决办法
3万
查看次数

如何在Angular2中正确使用依赖注入(DI)?

我一直试图弄清楚(DI)依赖注入如何在Angular2中工作.每当我尝试将服务/或类注入到我的组件中时,我遇到了很多问题/问题.

从不同的googled文章,我需要providers: []在组件配置中使用,或者有时我需要@Inject()在我的构造函数中使用或直接注入bootstrap(app, [service])?我也看到一些文章要我@injectable装扮装饰.

例如:要注入Http,我只需要将import{Http}Http放在提供程序中,但对于FormBuilder,我需要@Inject()在构造函数中使用.

什么时候使用什么有什么经验法则?你能提供一些示例代码片段吗?谢谢 :-)

angular2-services angular2-di angular

24
推荐指数
2
解决办法
2万
查看次数

从Angular2中的自定义验证器访问服务

我需要从静态方法中访问我的自定义http服务,例如:

import {Control} from 'angular2/common';
import {HttpService} from './http.service';

class UsernameValidator {
    static usernameExist(control: Control): Promise<ValidationResult> { 
        ... /* Access my HTTPservice here */
    }
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下如何访问服务?

angular2-forms angular2-di angular

16
推荐指数
1
解决办法
4223
查看次数

Angular 2 Di无法正常工作 - 无法解析所有参数

我已经创建了一个简单的Hello World应用程序.但是,当我想添加一个"服务"只是一个简单的Di我得到以下错误:

angular2.dev.js:23877 EXCEPTION:无法解析'AppComponent'(?)的所有参数.确保所有参数都使用Inject进行修饰或具有有效的类型注释,并且"AppComponent"使用Injectable进行修饰.

angular2-polyfills.js:469未处理的Promise拒绝:无法解析'AppComponent'(?)的所有参数.确保所有参数都使用Inject进行修饰或具有有效的类型注释,并且"AppComponent"使用Injectable进行修饰.; 区域:角; 任务:Promise.then; 值:

我有3个档案

boot.ts:

///<reference path="../../node_modules/angular2/typings/browser.d.ts"/>
import {bootstrap} from 'angular2/platform/browser'
import {AppComponent} from './mainApp'
bootstrap(AppComponent);
Run Code Online (Sandbox Code Playgroud)

mainApp.ts:

import {Component} from 'angular2/core';
import {CourseService} from './course.service';


@Component({
    selector: 'my-app',
    template: 'My First Angular 2 App',
    providers: [CourseService],
})
export class AppComponent {
    constructor(courseService: CourseService) {
    }
} 
Run Code Online (Sandbox Code Playgroud)

course.service.ts:

export class CourseService {
   public getCourses(): string[] {
      let courses: string[] = ["Course 1", "Course 2", "Course 3"];
      return courses;
  }
}
Run Code Online (Sandbox Code Playgroud)

当我从构造函数中删除参数时,每件事都可以正常工作.

这就是我的HTML文档的头部,我使用angular 2 beta 13:

<script …
Run Code Online (Sandbox Code Playgroud)

angular2-di angular

16
推荐指数
2
解决办法
2万
查看次数

Angular2传递函数作为组件输入不起作用

我有一个将函数作为输入的组件.我从父母传递了这个功能.

虽然调用了该函数,但该函数无法访问声明此函数的实例的依赖项.

这是组件

@Component({
  selector: 'custom-element',
  template: `
    {{val}}
  `
})
export class CustomElement {
  @Input() valFn: () => string;

  get val(): string {
    return this.valFn();
  }
}
Run Code Online (Sandbox Code Playgroud)

以下是组件的使用方法

@Injectable()
export class CustomService {
  getVal(): string {
    return 'Hello world';
  }
}

@Component({
  selector: 'my-app',
  template: `
   <custom-element [valFn]="customVal"></custom-element>
  `,
})
export class App {
  constructor(private service: CustomService) {
  }
  customVal(): string {
    return this.service.getVal();
  }
}
Run Code Online (Sandbox Code Playgroud)

当我运行这个应用程序时,我在控制台中收到错误说 Cannot read property 'getVal' of undefined

这是一个问题的掠夺者.

https://plnkr.co/edit/oQ229rXqOU9Zu1wQx18b?p=preview

angular2-template angular2-di angular

10
推荐指数
1
解决办法
1万
查看次数

如何在Angular 2中动态添加提供程序到注入器?

每个组件都可以使用ComponentMetadata中的"providers"属性指定新的Providers.

有没有办法从组件的构造函数动态指定提供程序?

angular2-di angular

9
推荐指数
3
解决办法
5186
查看次数

Angular 2 - 单身人士服务?

在Angular 1中,我经常使用工厂来提供服务,以存储许多组件可访问的共享状态.看起来在Angular 2中,每次都会创建注入@Injectable()的所有服务,从而失去共享状态.

我在根模块的providers元键上注册'服务,但我仍然得到一个瞬态实例.

是)我有的:

Injectable()
export class ArtistService {
   constructor(private http:Http) {
     // firing on each injection
     console.log("ArtistService ctor");
   }

}
Run Code Online (Sandbox Code Playgroud)

然后在组件中调用它:

@Component({
    selector: 'artist-display',
    templateUrl: './artistDisplay.html',
})
export class ArtistDisplay  {
    constructor(private artistService: ArtistService) {
           // instance is fine but transient
    }
}
Run Code Online (Sandbox Code Playgroud)

以及模块的定义:

@NgModule({
  declarations: [...],
  imports: [BrowserModule, FormsModule, HttpModule,
    RouterModule.forRoot(rootRouterConfig)],
  providers   : [
      ArtistService,

      // make sure you use this for Hash Urls rather than HTML 5 routing
      { provide: LocationStrategy, useClass: …
Run Code Online (Sandbox Code Playgroud)

angular2-di angular

7
推荐指数
1
解决办法
2万
查看次数

如何将angular2服务注入单元测试?(RC3)

我在用RC3.我正在实现Angular2这里记录的新路由器:https://angular.io/docs/ts/latest/guide/router.html

一切正常但我在单元测试中遇到问题.具体来说,我不能将Angular2服务注入我的单元测试中.

我的相关组件代码是:

import {Component} from '@angular/core';
import {ActivatedRoute} from '@angular/router';

@Component({
  templateUrl: ...
  styleUrls: ...
})

export class Route1DetailComponent {

  constructor(private route:ActivatedRoute) {
    console.log(route);
  }
}
Run Code Online (Sandbox Code Playgroud)

我的单元测试看起来像:

import {
  expect, it, iit, xit,
  describe, ddescribe, xdescribe,
  beforeEach, beforeEachProviders, withProviders,
  async, inject
} from '@angular/core/testing';

import {ActivatedRoute} from '@angular/router';
import {Route1DetailComponent} from './route1-detail.component';
import {TestComponentBuilder} from '@angular/compiler/testing';

describe('route1-detail.component.ts', () => {

  beforeEachProviders(() => [
    {provide: ActivatedRoute, useClass: ActivatedRoute}
  ]);

  it('should instantiate …
Run Code Online (Sandbox Code Playgroud)

angular2-routing angular2-di angular2-testing angular

5
推荐指数
1
解决办法
2848
查看次数