标签: angular2-services

如何在Angular2中使组件可以普遍访问

我基本上想要创建一个自定义对话框组件,我可以在我的Angular2应用程序中的任何位置使用它,无论应用程序树中的using组件位于何处.为简单起见,我们称之为SayHello组件.

考虑以下应用程序树:在此输入图像描述

所以,假设我想要SomeComponent.level3.component来调用SayHello.component中的对话框.

在Angular 1.x中,我会将RootScope注入控制器并以此方式点亮对话框.现在,我了解(或多或少)对于Angular2,你可以在组件树上冒泡事件(使用事件发射器),但是从树上的SomeComponent.level3.component向下到SayHello一直冒泡一个事件似乎很乏味. .零件.

所以我想我会创建一个SayHello服务,我会在任何想要点亮对话框的地方注入.这是我制定的代码草图.

myApp.component.ts

import {SayHelloComponent} from "<<folder>>/sayHello.component";
import {BunchOfComponents} from "<<folder>>/bunchOfComponents";

@Component({
    directives: [SayHelloComponent],
    selector: "my-app",
    templateUrl: `<bunch-of-components>Within this component exists
                      SomeComponent.level3.component </bunch-of-components>
                      <say-hello showdialog="{{showDialog}}" message="{{message}}">
                      </say-hello>`

})
export class myAppComponent {
    showDialog = false;
    message = "";

    constructor(private sayHelloService: SayHelloService) {
        this.showDialog = sayHelloService.showDialog;
        this.message = sayHelloService.message;

    }
}
Run Code Online (Sandbox Code Playgroud)

SayHelloService.ts

import {Injectable} from 'angular2/core';

@Injectable()
export class SayHelloService {
    public showDialog: boolean = false;
    public message: string ="";

    constructor() { …
Run Code Online (Sandbox Code Playgroud)

angular2-services angular

8
推荐指数
1
解决办法
4950
查看次数

Angular 2如何为延迟加载的模块提供单例服务

根据我的理解Angular 2 rc5,要从另一个模块(不是AppModule)作为单个模块提供服务到每个组件,即使是那些延迟加载的模块,我们也不会将该服务包含在该providers模块的其他模块中.我们改为导出它RouterModule.forRoot()并导入结果AppModule

根据文件:

SharedModule应仅在根AppModule导入时提供UserService.SharedModule.forRoot方法帮助我们应对这一挑战...... SharedModule没有providers...当我们将SharedModule添加到AppModule的导入时,我们调用forRoot.这样,AppModule获得导出的类,SharedModule同时提供单例UserService提供程序

我真的很挣扎如何为延迟加载的路由提供第三方服务(imports我的数组中的模块使用的服务AppModule).我无法控制这个第三方模块,所以我不能只从该NgModule.providers模块的数组中删除该服务,并将其放入RouterModule.forRoot()我的服务中.

具体的服务MdIconRegistry,这是providersMdIconModuleAngular Material 2 alpha 7-3.此服务用于注册svg图标,然后可以使用<md-icon svgIcon='iconName'>标记显示在页面上.所以:

  • MdIconModule在我的根目录中导入AppModule
  • 我使用有问题的服务来注册我的svg图标 AppComponent

该图标可见并且运行良好,但仅限于启动时加载的模块.延迟加载的模块无法看到这些图标,因此我怀疑Angular注入器不会注入相同的MdIconRegistry服务实例.

tl; dr:我怎样才能从第三方模块中将服务作为我的延迟加载组件的单例?

这是一个演示问题的编码器(编码typescript).

PS:这引起了github上MdIconModule开发人员的注意.

module typescript angular2-services angular

8
推荐指数
1
解决办法
3450
查看次数

如何在Angular 2中重新加载相同URL的组件?

我试图通过使用router.navigate重新加载Angular 2中的相同URL,但它无法正常工作.url:http:// localhost:3000/landing 场景:我在http:// localhost:3000/landing,现在我正在更改页面中应该重新加载页面的特定参数.

代码:

let link = ['Landing'];
this.router.navigate(link);
Run Code Online (Sandbox Code Playgroud)

frontend typescript angular2-routing angular2-services angular

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

Angular2的服务应该是无国籍的吗?

我来自Java世界,服务通常意味着无国籍.Angular2中的服务应该也是无状态的吗?或者我们可以简单地存储状态,因为我们不必像Java示例那样关心并发线程访问?

在AuthService类的https://angular.io/docs/ts/latest/guide/router.html#!#teach-authguard-to-authenticate中,存储状态.

它只是简化示例还是常见做法?我知道服务是实例化的,并且在声明它们的范围内存在,但这意味着我必须关心提供服务的位置以了解状态持续多长时间.

angular2-services angular

8
推荐指数
1
解决办法
2899
查看次数

订阅中的Angular2订阅

在Angular2中,基于第一个API调用的结果实现第二个API调用的正确方法是什么?我的一个Angular2组件有以下方法.我尝试在另一个订阅内完成订阅,第二个订阅的响应始终是"未定义".

根据CozyAzure的建议进行编辑.

export interface Result {
  host: string;
  resourceUri: string;
  groupId?: string;
  resource?: any;
}

private curateResults(searchTerm: string, searchResults: SearchResults): Result[] {
    const results: Result[] = [];
    if (searchResults.results !== undefined && searchResults.results.length > 0) {
      searchResults.results.forEach((result: any) => {
        const processedSearchResult: Result = {
          host: result.origin.toString(),
          resourceUri: result.url.toString()
        };
        processedSearchResult.resource = undefined;
        processedSearchResult.groupId = undefined;
        this.bopsHttpService.getResourceData(processedSearchResult.host, processedSearchResult.resourceUri)
          .flatMap((resource: any) => {
            processedSearchResult.groupId = this.getGroupIdFromResource(resource, 'groupId');
            if (processedSearchResult.groupId === undefined) {
              const uriParts = processedSearchResult.resourceUri.split('/');
              const predicate = uriParts[uriParts.length - …
Run Code Online (Sandbox Code Playgroud)

angular2-services angular

8
推荐指数
1
解决办法
8638
查看次数

如何在Angular 2中的服务中注入服务时传递依赖参数(Ionic 2/Angular 2/Typescript)

我正在制作一个示例应用程序来连接到离线2 in typescript中的websocket服务器.回到repo

我的要求是在应用程序启动期间进行websocket连接

我正在使用angular2-websocket来创建连接.

参考文献:

  1. http://blog.thoughtram.io/angular/2015/09/17/resolve-service-dependencies-in-angular-2.html

  2. http://blog.thoughtram.io/angular/2015/05/18/dependency-injection-in-angular-2.html

我收到错误"无法解析'$ WebSocket'的所有参数(字符串,数组,?).确保所有参数都使用Inject进行修饰或具有有效的类型注释,并且'$ WebSocket'使用Injectable进行修饰. "

代码: app.ts

import {App, Platform} from 'ionic-framework/ionic';
import {TabsPage} from './pages/tabs/tabs';
import {ConnectionService} from './framework/connection/connection-service'
import {$WebSocket} from 'angular2-websocket/angular2-websocket';
import {bootstrap} from 'angular2/platform/browser';

// https://angular.io/docs/ts/latest/api/core/Type-interface.html
import {Type} from 'angular2/core';


@App({
  template: '<ion-nav [root]="rootPage"></ion-nav>',
  config: {}
})
export class MyApp {
  rootPage: Type = TabsPage;

  constructor(platform: Platform, private conn : ConnectionService) {
    platform.ready().then(() => {
      this.conn.connect();
    });
  }
}
bootstrap(MyApp, [$WebSocket, ConnectionService]);
Run Code Online (Sandbox Code Playgroud)

连接service.ts

import {Injectable, Component, …
Run Code Online (Sandbox Code Playgroud)

typescript ionic-framework ionic2 angular2-services angular

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

Angular2:TypeError:无法读取未定义的属性'Symbol(Symbol.iterator)'

我是观察者的新手,并在Angular2博客中尝试了Christoph Burgdorf的Observables的基本自动完成变体.运行此代码会产生:

EXCEPTION:TypeError:无法读取未定义的属性'Symbol(Symbol.iterator)'

在ingredientservice ... rawsearch发出REST get调用之后.警报还会弹出[object Object]消息.我已经验证了端点运行正常.

任何有关如何调试此建议的建议将不胜感激.

ingredientservice.ts等待对文本字符串进行更改,对其进行去抖动并执行REST调用以从端点获取自动完成匹配.

import {Injectable} from 'angular2/core';
import {Http} from 'angular2/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/map';

@Injectable()
export class IngredientService {
  endpoint_url: String = "http://localhost:5000/ingredient/";
  results: Observable<Array<string>>;
  constructor(private http: Http) { }

  search(terms: Observable<string>, debounceDuration = 400) {
    return terms.debounceTime(debounceDuration)
      .distinctUntilChanged()
      .switchMap(term => this.rawSearch(term));
  }

  getData: Object[];
  rawSearch(term: string) {
    console.log(term);

    this.http.get(this.endpoint_url + term)
      .subscribe(
      res => {
        this.getData = res.json(); …
Run Code Online (Sandbox Code Playgroud)

angular2-services angular

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

catch不适用于http.get Angular2

我正在尝试使用Http服务进行ajax调用,这工作正常.

现在我想处理失败案件.例如,如果我们得到404或任何其他错误.

我使用以下代码.

import {Component,Inject} from '@angular/core';
import {Http, Response,HTTP_PROVIDERS} from '@angular/http';
import {DoService} from './service';
import 'rxjs/Rx';
import 'rxjs/add/operator/catch';

@Component({
    selector: 'comp-one',
    template: `<h2>My First Angular 2 App</h2>{{data}}
        <input type="button" (click)="doSomething()" value="Do Http"/>`
})

export class ComponentOne { 
    constructor(public _http:Http){
    console.log("It is from ComponentOne constructor..");
        this._http = _http;
    }
    data:Object;
    doSomething(){
        console.log("It is from doSomething ComponentOne");
        let temp:any = this._http.get('people.json')//people.json is not exist, intendedly maing any error
     .map(res => res.json())
        .catch((err:any)=>{ console.log("Something is wrong..")});// If i keep this line …
Run Code Online (Sandbox Code Playgroud)

angular2-services angular

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

茉莉花:预期在异步函数中引发错误

我的angular2应用程序中有一个异步函数,我想为其编写单元测试。想象一下我的函数是这样的:

myFunc(a: int): Promise<void> {
    if (a == 1)
        throw new Error('a should not be 1');

    let body = {
        value: a
    };
    return apiService.patch('/url/', JSON.stringify(body)).toPromise();
}
Run Code Online (Sandbox Code Playgroud)

现在,我正在考虑检查是否满足条件。我尝试了以下代码;但是,此测试始终失败,因为我的代码实际上并不等待任何结果:

it('should throw error if a = 1', () => {
    expect(() => {
        mySerivce.myFunc(1);
    }).toThrow(new Error('a should not be 1'));
})
Run Code Online (Sandbox Code Playgroud)

我不知道该如何为这些类型的逻辑编写单元测试...

unit-testing jasmine typescript angular2-services angular

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

如何从角度为 6 的数组中删除重复的对象

我正在尝试删除数组中的重复值对象但不起作用...我认为重复函数正在运行但未反映在li列表中。你能找出我必须改变的地方吗?

我的服务文件:

 addComp(Names,c){   
 this.item.push({ name: Names, componentid: c});
 this.uniqueArray = this.removeDuplicates(this.item, "name"); //this line issue
 this.item=this.uniqueArray; //this line issue
 }
Run Code Online (Sandbox Code Playgroud)

typescript angular2-services angular angular5 angular6

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