我创建了AngularJS 2服务,并在2个不同的组件中使用它:App-Component&Sub-Component.每个输出属性'log'(一个字符串)我的服务.
StateService类:
@Injectable ()
class StateService {
public log : string;
static count : number = 0;
constructor () {
this.log = '';
StateService.count++;
this.writeToLog ('CREATED '+StateService.count+' at ' + new Date().toString());
}
public writeToLog (text : string) : void {
this.log += text + '\n';
}
}
Run Code Online (Sandbox Code Playgroud)
零件 :
@Component ({
selector : 'Sub-Component',
template : `<hr>
This is the Sub-Component !
<BR>
StateService Log :
<pre>{{ _stateService.log }}</pre>
<button (click)="WriteToLog ()">Write to log</button>
`,
providers : [StateService] …Run Code Online (Sandbox Code Playgroud) 嗨我正在尝试接收来自catch块(服务)发送的错误.在多个组件中,我需要显示弹出窗口并显示错误消息.请让我知道如何创建一个通用方法并在服务块内调用它.就像我现在用"showErrorPage()"做的那样.
import { Injectable } from '@angular/core';
import { Http, Headers, Response, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map'
@Injectable()
export class DataService {
private reqData = {};
private url: string;
constructor(private http: Http) {
}
getResult(searchObject: {}): Observable<Response> {
// some logic
return this.http.post(<my url>, <data to be sent>)
.map((response: Response) => {
return response;
})
.catch((error: any) => {
if (error.status === 302 || error.status === "302" ) {
// do some thing …Run Code Online (Sandbox Code Playgroud) // Part of service
public someEvent: EventEmitter<number> = new EventEmitter();
....
// Component
@Component({
selector: 'some-component',
template: `...`
})
export class SomeComponent {
constructor(public service: Service) {
this.service.someEvent.subscribe((x) => {
// Do something
});
}
}
Run Code Online (Sandbox Code Playgroud)
SomeComponent在/路线中显示.当我在我的应用程序中导航到不同的路径并再次返回时,SomeComponent将再次订阅该事件,导致回调触发两次.如何订阅一次事件或取消订阅组件的破坏并再次订阅?
// Can't subscribe after.
ngOnDestroy() {
this.service.someEvent.unsubscribe();
}
Run Code Online (Sandbox Code Playgroud) 我试图将http提供程序导入服务,但是我收到以下错误:
无法解析'AppService'(?)的所有参数.确保所有参数都使用Inject进行修饰或具有有效的类型注释,并且"AppService"使用Injectable进行修饰.
以下是一些代码段:
<script src="~/es6-shim/es6-shim.min.js"></script>
<script src="~/systemjs/dist/system-polyfills.js"></script>
<script src="~/angular2/bundles/angular2-polyfills.js"></script>
<script src="~/systemjs/dist/system.src.js"></script>
<script src="~/rxjs/bundles/Rx.js"></script>
<script src="~/angular2/bundles/angular2.dev.js"></script>
<script src="~/angular2/bundles/http.dev.js"></script>
<!-- 2. Configure SystemJS -->
<script>
System.config({
map: { 'rxjs': 'RCO/rxjs' },
packages: {
RCO: {
format: 'register',
defaultExtension: 'js'
},
'rxjs': {defaultExtension: 'js'}
}
});
System.import('RCO/Areas/ViewOrganization/AngularTemplates/boot')
.then(null, console.error.bind(console));
Run Code Online (Sandbox Code Playgroud)
boot.ts
import {bootstrap} from 'angular2/platform/browser'
import {HTTP_PROVIDERS} from 'angular2/http'
import 'rxjs/add/operator/map'
import {AppComponent} from 'RCO/Areas/ViewOrganization/AngularTemplates/app.component'
import {AppService} from 'RCO/Areas/ViewOrganization/AngularTemplates/app.service'
bootstrap(AppComponent, [HTTP_PROVIDERS, AppService]);
Run Code Online (Sandbox Code Playgroud)
app.service.ts
import {Injectable} from 'angular2/core';
import {Http, Response} from 'angular2/http';
import {Observable} …Run Code Online (Sandbox Code Playgroud) typescript systemjs angular2-services angular2-injection angular
我想在这里主要使用接受的答案来试验forkJoin:
可观察变量的Angular2 Observable.forkJoin - ReferenceError:未定义Observable
我收到上面的错误消息,因为forkJoin不可用.
谁知道为什么?
我有一个父服务,有一些依赖,如
@Injectable()
export class ParentService{
constructor(private http:Http, private customService:CustomService){}
}
Run Code Online (Sandbox Code Playgroud)
我想扩展服务
@Injectable()
export class ChildService extends ParentService{
constructor (){
super(??) <= typescript now asking to enter two parameters according to ParentServie's constructor
}
}
Run Code Online (Sandbox Code Playgroud)
编辑 - - - - - - - - -
@Injectable()
export class ParentService{
constructor(private http:Http, private customService:CustomService){}
get(){this.http.get(...)}
}
@Injectable()
export class ChildService extends ParentService{
constructor (private http:Http, private customService:CustomService){
super(http, customService)
}
}
Run Code Online (Sandbox Code Playgroud)
然后我可以在组件中使用?
export class Cmp {
constructor(private childService:ChildService){
this.childService.get()
}
}
Run Code Online (Sandbox Code Playgroud) 我已经构建了一个ErrorHandlerLogger,它是一个扩展ErrorHandler并将错误消息记录到远程存储库的服务.
ErrorHandlerLogger需要HttpModule提供的Angular http客户端.
在ErrorHandlerModule中,我导入HttpModule并将ErrorHandlerLogger定义为提供者.
在AppModule中我导入ErrorHandlerModule.
当我启动应用程序时,我收到以下错误消息
Uncaught Error: Can't resolve all parameters for ErrorHandlerLogger: (?).
Run Code Online (Sandbox Code Playgroud)
在这里我的代码
ErrorHandlerModule
import { NgModule, ErrorHandler } from '@angular/core';
import { HttpModule } from '@angular/http';
import {ErrorHandlerLogger} from './error-handler-logger';
@NgModule({
declarations: [],
exports: [],
imports: [
HttpModule
],
providers: [
{provide: ErrorHandler, useClass: ErrorHandlerLogger}
]
})
export class ErrorHandlerModule {}
Run Code Online (Sandbox Code Playgroud)
ErrorHandlerLogger
import { ErrorHandler } from '@angular/core';
import { …Run Code Online (Sandbox Code Playgroud) 我知道提供者是从另一个类获得服务但是什么是多提供者和令牌的东西?
还有什么时候multi=true呢?
provide(NG_VALIDATORS, { useExisting: class), multi: true })
Run Code Online (Sandbox Code Playgroud) angular2-forms angular2-directives angular2-services angular
我一直试图弄清楚(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) angular ×10
typescript ×2
angular2-di ×1
eventemitter ×1
extends ×1
rxjs ×1
rxjs5 ×1
systemjs ×1