我一直试图弄清楚(DI)依赖注入如何在Angular2中工作.每当我尝试将服务/或类注入到我的组件中时,我遇到了很多问题/问题.
从不同的googled文章,我需要providers: []在组件配置中使用,或者有时我需要@Inject()在我的构造函数中使用或直接注入bootstrap(app, [service])?我也看到一些文章要我@injectable装扮装饰.
例如:要注入Http,我只需要将import{Http}Http放在提供程序中,但对于FormBuilder,我需要@Inject()在构造函数中使用.
什么时候使用什么有什么经验法则?你能提供一些示例代码片段吗?谢谢 :-)
我正在尝试扩展angular 2 http类,以便能够处理全局错误并为我的secureHttp服务设置标头.我找到了一些解决方案,但它不适用于Angular 2的最终版本.有我的代码:
文件:secureHttp.service.ts
import { Injectable } from '@angular/core';
import { Http, ConnectionBackend, Headers, RequestOptions, Response, RequestOptionsArgs} from '@angular/http';
@Injectable()
export class SecureHttpService extends Http {
constructor(backend: ConnectionBackend, defaultOptions: RequestOptions) {
super(backend, defaultOptions);
}
}
Run Code Online (Sandbox Code Playgroud)
文件:app.module.ts
import { BrowserModule, Title } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { routing } from './app.routes';
import { AppComponent } from './app.component';
import { HttpModule, Http, XHRBackend, RequestOptions } from '@angular/http';
import { CoreModule } from './core/core.module';
import {SecureHttpService} …Run Code Online (Sandbox Code Playgroud) 在角度为2的angular.io教程的服务部分,我点击了一个名为of.for的方法,例如:
getHeroes(): Observable<Hero[]> {
return of(HEROES);
}
Run Code Online (Sandbox Code Playgroud)
或在下面的样本:
getHero(id: number): Observable<Hero> {
// Todo: send the message _after_ fetching the hero
this.messageService.add(`HeroService: fetched hero id=${id}`);
return of(HEROES.find(hero => hero.id === id));
}
Run Code Online (Sandbox Code Playgroud)
在angular.io刚刚解释
使用()的RxJS返回一个模拟英雄的Observable(Observable).
并没有解释为什么我们应该使用功能,它究竟做了什么,它有什么好处?
我有一个服务,像这样:
@Injectable()
export class EditorService { ... }
Run Code Online (Sandbox Code Playgroud)
我有一个组件,像这样:
@Component({
...
template: `<child-component></child-component>`,
providers: [EditorService],
...
})
export class SomeComponent {
constructor(
private _appleEditorService: EditorService,
private _pearEditorService: EditorService) {}
}
Run Code Online (Sandbox Code Playgroud)
您可能已经注意到,此组件具有子组件:
@Component({
...
selector: 'child-component',
...
})
export class ChildComponent {
constructor(
private _appleEditorService: EditorService,
private _pearEditorService: EditorService) {}
}
Run Code Online (Sandbox Code Playgroud)
如您所见,我想要两个我的实例EditorService:一个用于编辑苹果,一个用于编辑梨.但是,上面的代码不起作用,因为Angular无法知道哪个实例的EditorService变量名是私有的._pearEditorService在ChildComponent还不如指同一个实例_appleEditorService中SomeComponent.
问题:那么,我可以两次使用相同的Angular2服务吗?
编辑:我的问题的关键是如果可以使用相同的类.我知道有一些解决方法是为服务的每个实例创建一个单独的类,甚至通过继承实现少量代码.我只是想知道是否可以不用.
Angular版本:2.0.0-beta.13
我想注入http一项服务:
@Injectable()
export class GithubService {
...
constructor(private http: Http) {
}
}
Run Code Online (Sandbox Code Playgroud)
我已HTTP_PROVIDERS在应用程序的根组件中列为提供程序,因此该提供程序应该可用于我的应用程序中的任何组件:
@Component({
providers: [HTTP_PROVIDERS],
})
export class AppComponent {}
Run Code Online (Sandbox Code Playgroud)
但是,当我运行此应用程序时,我收到以下错误:
例外:错误:未捕获(承诺):没有Http的提供者!(HttpReqComponent - > GithubService - > Http)
我究竟做错了什么?
编辑
我改变providers了viewProviders,错误现在消失了!
@Component({
viewProviders: [HTTP_PROVIDERS],
})
export class AppComponent {}
Run Code Online (Sandbox Code Playgroud)
但是,我无法解释为什么这是有效的.http任何视图都不会直接访问.它只能在里面进入GithubService.那我为什么要宣布HTTP_PROVIDERS为viewProvider?
编辑2
好吧,我将providersAppComponent 的声明向下移动到我需要它的组件,现在它可以工作了!因此,在根级别声明它必定有一些怪癖.
@Component({
providers: [HTTP_PROVIDERS, GithubService],
})
export class HttpReqComponent { }
Run Code Online (Sandbox Code Playgroud)
其实,无论是providers和viewProviders作品.事实证明,这viewProviders …
我的角度2项目中有一个表格.
我知道如何从API中检索数据.但是不知道如何在那里执行CRUD操作.
任何人都可以帮我解决如何以JSON格式将表单数据发送到PHP /任何其他语言的Web服务的简单代码...
帮助将不胜感激.谢谢
在使用Angular 2和多种计算服务编写应用程序时,我遇到了以下问题:
这是类的快照,它为我提供了多种计算方法,并在应用程序级别实例化:
@Injectable()
export class FairnessService {
constructor(){}
private static calculateProcentValue(value: number, from: number): number {
return (Math.abs(value) / Math.abs(from)) * 100;
}
public static calculateAllocationWorth(allocation: Allocation): number {
...
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢你的帮助.
我有一个组件从服务器获取项目列表,然后使用模板中的*ngFor显示该列表.
我希望列表显示一些动画,但一个接一个.我的意思是每个列表项应该在其他之后动画.
我正在尝试这样的事情:
import { Component, Input, trigger, state, animate, transition, style } from '@angular/core';
@Component({
selector: 'list-item',
template: ` <li @flyInOut="'in'">{{item}}</li>`,
animations: [
trigger('flyInOut', [
state('in', style({ transform: 'translateX(0)' })),
transition('void => *', [
style({ transform: 'translateX(-100%)' }),
animate(100)
]),
transition('* => void', [
animate(100, style({ transform: 'translateX(100%)' }))
])
])
]
})
export class ListItemComponent {
@Input() item: any;
}
Run Code Online (Sandbox Code Playgroud)
在我的列表组件模板中我使用它像:
<ul>
<li *ngFor="let item of list;">
<list-item [item]="item"></list-item>
</li>
</ul>
Run Code Online (Sandbox Code Playgroud)
它的作用是立即显示整个列表.我希望项目一个接一个地输入一些动画.
我有一个Angular 2服务,它需要在初始化时进行异步工作,并且在初始化完成之前不应该可用.
@Injectable()
export class Api {
private user;
private storage;
constructor(private http: Http) {
this.storage = LocalStorage;
this.storage.get('user').then(json => {
if (json !== "") {
this.user = JSON.parse(json);
}
});
}
// one of many methods
public getSomethingFromServer() {
// make a http request that depends on this.user
}
}
Run Code Online (Sandbox Code Playgroud)
按照目前的情况,此服务已初始化,并立即返回到使用它的任何组件.然后该组件调用getSomethingFromServer()它ngOnInit,但此时Api.user未初始化,因此发送了错误的请求.
生命周期钩子(OnInit,OnActivate等)不能用于服务,只能用于组件和指令,所以我不能使用它们.
从get()调用中存储Promise 将需要依赖于用户的所有不同方法等待它,从而导致大量代码重复.
在Angular 2中进行异步初始化服务的推荐方法是什么?
我想知道我是否可以在没有订阅回调的情况下制作一个http post请求,就像这样
this._http.post('/list/items/update?itemId=' + itemId + "&done=" + done, null);
Run Code Online (Sandbox Code Playgroud)
而不是这个
this._http.post('/list/items/update?itemId=' + itemId + "&done=" + done, null)
.subscribe();
Run Code Online (Sandbox Code Playgroud)