标签: angular2-services

如何在 Angular 4/5 上将延迟加载模块中的拦截器添加到应用程序拦截器数组中?

我有AppModule和LazyLoadedModule。我想要从每个模块组件中得到的是:

  1. 来自 AppModule 组件的请求使用LoggerInterceptor和UrlInterceptor;
  2. 来自 LazyLoadedModule 组件的请求使用LoggerInterceptor、UrlInterceptor以及FilterInterceptor。

应用程序模块.ts

@NgModule({
  bootstrap: [AppComponent],
  declarations: [
    AppComponent,
  ],
  imports: [
    CoreModule,
    HttpClientModule,
  ],
  providers: [
     {provide: HTTP_INTERCEPTORS,useClass: LoggerInterceptor,multi: true},
     { provide: HTTP_INTERCEPTORS, useClass: UrlInterceptor, multi: true }
  ],
})
export class AppModule {}
Run Code Online (Sandbox Code Playgroud)

延迟加载.module.ts

@NgModule({
  declarations: [
    LazyLoadedComponent,
  ],
  providers: [
     { provide: HTTP_INTERCEPTORS, useClass: FilterInterceptor, multi: true }
  ],
})
export class LazyLoadedModule {}
Run Code Online (Sandbox Code Playgroud)

问题是,当 LazyLoadedModule 延迟加载时,FilterInterceptor …

javascript dependency-injection angular-http-interceptors angular2-services angular

6
推荐指数
1
解决办法
2648
查看次数

在Angular 2.0中注入服务提供者

在AngularJS 2.0 Heroes教程解释中,它指出如果子组件在其@Component Providers列表中包含服务,则Angular将创建特定于该子组件的该服务的单独实例.我不明白的是,如果有时您想要独立使用子组件,而有时在父组件中使用子组件,您会怎么做.这似乎是一个严重的限制.我刚刚玩Angular 2.0,所以很可能我误解了一些东西.

以下是来自Heroes Tutorial服务部分的Angular.io网站的解释.

附录:隐藏父母的服务

我们之前说过,如果我们将父AppComponent HeroService注入HeroDetailComponent,我们不能将提供者数组添加到HeroDetailComponent元数据中.

为什么?因为这告诉Angular在HeroDetailComponent级别创建HeroService的新实例.HeroDetailComponent不需要自己的服务实例; 它想要它的父服务实例.添加providers数组会创建一个影响父实例的新服务实例.

仔细考虑注册提供商的地点和时间.了解该注册的范围.注意不要在错误的级别创建新的服务实例.

这是指向将其置于上下文中的页面的链接.

angular2-services angular

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

角度2更新应用程序组件从路由器出口组件

我正在使用angular 2 rc1和新路由器@ angular/router

在应用程序组件中,我有一个导航部分和路由器插座

<nav>   
    <a *ngIf="auth?.userName == null" [routerLink]="['/login']">Login</a>
    <a *ngIf="auth?.userName != null" (click)="logout()">Logout</a>
    {{auth?.userName}}
</nav> 
<router-outlet></router-outlet>
Run Code Online (Sandbox Code Playgroud)

我将一个loginService注入app组件并订阅ngOnInit中的一个事件

ngOnInit() {
    this.loginService.loginSuccess.subscribe(this.loginSuccess);

} 
ngOnDestroy() {
    this.loginService.loginSuccess.unsubscribe();
}
private loginSuccess(res: IAuthResponse) {
    this.auth = res;
}  
Run Code Online (Sandbox Code Playgroud)

当我导航到我的'/ login'路由页面/组件时,我的loginService是inject,loginService定义了一个事件

@Output() loginSuccess = new EventEmitter<IAuthResponse>();
Run Code Online (Sandbox Code Playgroud)

在成功登录我的服务后,登录服务会引发该事件

this.loginSuccess.next(response);
Run Code Online (Sandbox Code Playgroud)

我能够在订阅的loginSucess上的app组件中设置断点,并且数据被传递,但是'this'是未定义的.

private loginSuccess(res: IAuthResponse) {
    this.auth = res;  //this is undefind
} 
Run Code Online (Sandbox Code Playgroud)

如何从在路由器插座中托管的组件中使用的服务触发的事件更新应用程序组件

angular2-routing angular2-services angular

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

迭代Angular 2中的一组对象

我有一个从json文件服务文件中收到的对象数组.当我在组件中订阅它并尝试迭代它时,我收到以下错误:

EXCEPTION: Error in app/dashboard/features/fleet/fleetControlPanel/fleetControlPanelTemplate.html:38:14BrowserDomAdapter.logError @ browser_adapter.ts:78BrowserDomAdapter.logGroup @ browser_adapter.ts:89ExceptionHandler.call @ exception_handler.ts:53(anonymous function) @ application_ref.ts:304schedulerFn @ async.ts:131SafeSubscriber.__tryOrUnsub @ Subscriber.ts:240SafeSubscriber.next @ Subscriber.ts:192Subscriber._next @ Subscriber.ts:133Subscriber.next @ Subscriber.ts:93Subject._finalNext @ Subject.ts:154Subject._next @ Subject.ts:144Subject.next @ Subject.ts:90EventEmitter.emit @ async.ts:117NgZone._zoneImpl.ng_zone_impl_1.NgZoneImpl.onError @ ng_zone.ts:138NgZoneImpl.inner.inner.fork.onHandleError @ ng_zone_impl.ts:90ZoneDelegate.handleError @ zone.js:327Zone.runGuarded @ zone.js:233NgZoneImpl.runInnerGuarded @ ng_zone_impl.ts:100NgZone.runGuarded @ ng_zone.ts:216outsideHandler @ dom_events.ts:16ZoneDelegate.invokeTask @ zone.js:356Zone.runTask @ zone.js:256ZoneTask.invoke @ zone.js:423
EXCEPTION: TypeError: Cannot read property 'length' of undefined

TypeError: Cannot read property 'length' of undefined
        at FleetSummaryComponent.ngOnChanges (fleetSummaryComponent.ts:62)
        at DebugAppView._View_FleetControlPanelComponent2.detectChangesInternal (FleetControlPanelComponent.template.js:755)
        at DebugAppView.AppView.detectChanges (view.ts:243)
        at DebugAppView.detectChanges (view.ts:345)
        at …
Run Code Online (Sandbox Code Playgroud)

loops observable angularjs angular2-services angular

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

在angular2的控制台上注入服务

如何在控制台的angular2中注入服务?

在angular1中刚刚写道:

angular.element(document).injector().get('MyService')
Run Code Online (Sandbox Code Playgroud)

inject angular2-services angular

5
推荐指数
0
解决办法
1449
查看次数

使用注入的角度服务作为静态方法中的依赖项

我试图在静态方法中使用注入的依赖关系,当然注入的依赖关系是实例范围的,不能在静态方法中使用。

这是我的课:

@Injectable()
export class PasswordValidationService {

  constructor(private userAccountService:UserAccountService) {
  }

  static passwordValidator(control:AbstractControl) {
    return control
      .valueChanges
      .debounceTime(400)
      .switchMap(()=> this.userAccountService.checkCurrentPassword(control.value))
      .map(res=> {
          if (res.json() === true) {
            return null;
          }
          else {
            return {invalid: true};
          }
        }
      );
  }

}
Run Code Online (Sandbox Code Playgroud)

我的问题是UserAccountService在静态方法中使用(依赖项)的最佳实践是什么?

编辑:我重新设计了我的应用程序,使其使用实例方法而非静态方法,如下所示:

这是验证器:

import {Injectable} from "@angular/core";
import {UserAccountService} from "../../useraccount/useraccount.service";
import {AbstractControl} from "@angular/common";
import {Observable} from "rxjs/Observable";


@Injectable()
export class PasswordValidationService {

  constructor(private userAccountService:UserAccountService) {
  }

  passwordValidator(control:AbstractControl):Observable<any> {
    let validationResult = …
Run Code Online (Sandbox Code Playgroud)

typescript angular2-services angular

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

Angular 2跨组件共享websocket服务

我正在使用angular 2构建一个Web应用程序,其中我希望有多个组件监听同一个服务.此服务返回一个observable,它返回来自websocket的传入数据.我根据这个例子编写了代码.

当前的问题是: 数据从主组件通过服务发送到服务器(使用websockets)并返回数据.但是,只有home.component中的观察者被调用(具有id:room.created和data),而不是导航栏中的观察者.

有人能告诉我为什么两个都不叫?我也尝试将消息$ .subscribe添加到app.component但无济于事.

现在,让我们来看看代码.

返回可观察的消息服务.组件使用此服务发送和接收消息.

@Injectable()
export class MessageService {
    private _messages: Rx.Subject<Message>;
    messages$: Rx.Observable<Message>;

    constructor(wsService: SocketService, private configuration: Configuration) {
      console.log('messag eservice');
      this._messages = <Rx.Subject<Message>>wsService
        .connect()
        .map((response: MessageEvent): Message => {
            let data = JSON.parse(response.data);
            return {
                id: data.id,
                data: data.data,
            }
        });

      this.messages$ = this._messages.asObservable();
    }

    public send(message: Message): void {
      this._messages.next(message);
    }
} 
Run Code Online (Sandbox Code Playgroud)

一种套接字服务,它创建一个websocket连接并将自身绑定到此套接字的输入和输出.

import { Injectable } from '@angular/core';
import * as Rx from "rxjs/Rx";
import { Configuration } from '../app.constants'; …
Run Code Online (Sandbox Code Playgroud)

components websocket rxjs angular2-services angular

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

angular2 http.get()不向服务器发送请求

我正试图从我的角度应用程序对localhost执行一个get请求到我的api.但由于某种原因,角度http客户端似乎不执行get请求.

我可以在我的api服务器上看到没有得到请求.这导致了错误.api工作正常我试着做一个卷曲,我得到了预期的结果.

EXCEPTION:未捕获(在promise中):TypeError:无法读取未定义的属性'subscribe'

api.service

import { Injectable } from '@angular/core';
import { Headers, Http, Response, URLSearchParams, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Rx';

@Injectable()
export class ApiService {
    headers: Headers = new Headers({
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    });

    api_url: string = 'http://localhost:5001';

    constructor(private http: Http) { }

    private getJson(response: Response) {
        return response.json().results;
    }

    checkForError(response: Response): Response {
        if (response.status >= 200 && response.status < 300) {
            return response;
        } else {
            var error = new Error(response.statusText); …
Run Code Online (Sandbox Code Playgroud)

api get http angular2-services angular

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

Angular 2.1.2/2.2.0依赖注入实例未定义

在将我的代码从RC4移动到2.1.2期间,我遇到了一个奇怪的问题:我的所有构造函数参数都未定义其值.

我试图将提供商从组件移动到app.module.ts到app.component.ts.它们都不起作用.

2.1.2中有哪些新功能可以使依赖注入器注入"未定义"而不是创建/提供服务实例?

笔记

  1. 为了简化操作,我将代码更改为以下内容
  2. 没有错误消息.
  3. 如果我不将@Injectable()添加到AppComponent,我会得到 Can't resovle all parameters for AppComponent (?,?,?)
  4. 请注意,根注入器无法同时创建用户服务和路由器实例以提供AppComponent构造函数.
  5. AuthService用于注入Http,但我将其与其他代码一起删除,以便谜题中的变量更少.
  6. 尝试在Angular 2.2.0中也不起作用.

还有什么输入?

app.component.ts

import { Component,Injectable }       from '@angular/core'; 
import { Router  } from '@angular/router'; 
import { AuthService }  from '../login/auth.service';

@Component({
  selector: 'my-app',
  template: `
    <h1 class="title">Angular Router</h1>
    <nav>
    </nav>
    <router-outlet></router-outlet>
  `
})
@Injectable()
export class AppComponent {
  constructor(                            // debug here
              private auth: AuthService,  // auth = undefined
              private router: Router,     // router = undefined
              ) {
                console.log("AppComponent constructor");
              }  
} …
Run Code Online (Sandbox Code Playgroud)

typescript angular2-routing angular2-services angular

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

Angular2:数据层的最佳实践

我是Angular2的新手,正在边做边学.现在,我已成功构建了一个包含父组件,多个子组件和数据库服务的多视图.现在我将要使用各自的父子组件来实现其他视图.

应用程序应该使用可以在其他组件中添加/更新/删除的相同数据集,因此我正在寻找一个单独的数据层,可以由应用程序的所有组件直接查询.更多 - 我需要相同的服务实例,以便中间数据随处可用,以及避免不必要的数据库访问.在Angular2中定义和使用这样一个类的最佳方法是什么?

更新问: 现在,当我可以直接访问整个应用程序中数据层的同一实例的变量时,处理组件中变量的最佳方法是什么?

a)我应该使用本地组件变量,它们是相同数据层变量的副本(因此显式加载,获取和设置它们),如

this.locations = this.datalayer.locations;
this.selectedLocation;

updateLocation(id) {
  this.selectedLocation = id;
  this.datalayer.setSelectedLocation(id);
}

getSelectedLocation() {
   return this.selectedLocation;
}
Run Code Online (Sandbox Code Playgroud)

或者b)我应该专门处理数据层变量,迭代它们,从组件中获取和设置它们吗?

updateLocation(id) {
   this.datalayer.selectedLocation = id;
}

getSelectedLocation() {
   return this.datalayer.selectedLocation;
}
Run Code Online (Sandbox Code Playgroud)

或者可能有一个选项c?

data-layers typescript angular2-routing angular2-services angular

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