标签: angular2-services

Angular 2服务未注入组件

我在Angular2(2.0.0-beta.0)应用程序中定义了一个服务.它是这样的:

import {Injectable} from "angular2/core";

@Injectable()
export class MyService {
    constructor() {

    }

    getSomething() {
        return 'something';
    }
}
Run Code Online (Sandbox Code Playgroud)

我把它放在我的主应用程序文件中的bootstrap()函数中,以便它通常可用于我的代码:

bootstrap(App, [MyService, SomeOtherService, ROUTER_DIRECTIVES[);
Run Code Online (Sandbox Code Playgroud)

有时我不能在组件中使用该服务,即使我myService:MyService在组件constructor()函数中有类似的东西,如下所示:

import {MyService} from '../services/my.service';

@Component({
    selector: 'my-component',
    directives: [],
    providers: [],
    pipes: [],
    template: `
    <div><button (click)="doStuff()">Click Me!</button></div>
    `
})
export MyComponent {
    constructor(myService:MyService) {} // note the private keyword

    doStuff() {
        return this.myService.getSomething();
    }
}
Run Code Online (Sandbox Code Playgroud)

在其他地方它工作正常.在它不起作用的地方,我收到一条消息,如果我尝试访问它:

EXCEPTION: TypeError: Cannot read property 'getSomething' of undefined
Run Code Online (Sandbox Code Playgroud)

它基本上意味着服务没有注入.

是什么导致它不被注射?

typescript angular2-services angular2-injection angular

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

Angular 2 - 您如何订阅多个变量?

使用Angular 2,我从服务接收JSON数据.像这样的东西:

{
    "customerName": "foo",
    "customerAddress": "123 Somewhere",
    "products": 
    [
        {
            "productName": "bar",
            "productNumber": 123 
        },
        {
            "productName": "baz",
            "productNumber": 456             
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

在我的组件中,我订阅了服务以获取填充customerData.

private _getData() {
    this._myService
        .getData()
        .subscribe(
            customerData => this.customerData = customerData,
            error => this.errorMessage = error
        );
}
Run Code Online (Sandbox Code Playgroud)

此代码正常工作.

在JSON转储中,有两个数据"分组",即客户数据和产品数据,后者在数组中.理想情况下,我想分别填充产品数据.像这样的东西:

        .subscribe(
            customerData => this.customerData = customerData,
            productData => this.productData = customerData.products
            error => this.errorMessage = error
        );
Run Code Online (Sandbox Code Playgroud)

这是可能的,如果是这样,我将如何编码订阅?

angular2-services angular

4
推荐指数
1
解决办法
4386
查看次数

Angular2注入的自定义服务未定义

我试图将一个自定义服务(MessageService)注入另一个自定义服务(ItemService).它抛出一个错误MessageService在ItemService中被取消.
但是服务(MessageService和ItemService)都可以正常使用组件.

mani.ts

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';
const platform = platformBrowserDynamic();
platform.bootstrapModule(AppModule);
Run Code Online (Sandbox Code Playgroud)

app.module.ts

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent }   from './app.component';
import { routing, routedComponents } from './app.routing';
import { ItemService } from './services/item.service';
import { MessageService } from './services/message.service';
import …
Run Code Online (Sandbox Code Playgroud)

angular2-services angular

4
推荐指数
1
解决办法
1746
查看次数

Angular2 - 使用服务的组件之间的交互

我有两个组件A和B,其中组件A包含一个按钮.我希望当用户点击此按钮时,在组件B上触发一个功能

<A></A>
<router-outlet></router-outlet>
Run Code Online (Sandbox Code Playgroud)

并且组件B使用routing进行渲染.我正在考虑使用具有可观察布尔值的服务,该服务指示是否单击了A中的按钮.这是实现它的正确方法吗?

typescript angular2-routing angular2-services angular

4
推荐指数
1
解决办法
5171
查看次数

无法解析AuthenticationService的所有参数:([object Object],?,[object Object])

我遇到了下一个错误,无法理解如何解决它.

无法解析AuthenticationService的所有参数:([object Object],?,[object Object])

我已经检查了几乎每个主题,并尝试了多种方法来解决它,但仍然无法在第二天击败它.

我试图像这样在appService中注入第一个authService但是得到了同样的错误

@Inject(forwardRef(() => AuthenticationService)) public authService: AuthenticationService
Run Code Online (Sandbox Code Playgroud)

我检查了所有DI和服务内部的导入顺序,在我看来一切都是正确的

如果有人可以帮我处理它,我感激不尽.

Angular 4.0.0

AuthService

    import { Injectable } from '@angular/core';
import {Http, Headers, Response} from '@angular/http';
import 'rxjs/add/operator/toPromise';
import {Observable} from 'rxjs/Rx';

import {AppServices} from "../../app.services";
import {Router} from "@angular/router";

@Injectable()
export class AuthenticationService {
  public token: any;

  constructor(
    private http: Http,
    private appService: AppServices,
    private router: Router
  ) {
    this.token = localStorage.getItem('token');
  }

  login(username: string, password: string): Observable<boolean> {
    let headers = new Headers();
    let body …
Run Code Online (Sandbox Code Playgroud)

typescript angular2-services angular

4
推荐指数
1
解决办法
4898
查看次数

从Angular 2中的Hal + JSON对象解析信息

我有一个spring-data-rest存储库,它产生一个hal + json对象,我希望我的Angular 2前端能够接收和显示.

Hal + Json对象:

{
  "_embedded" : {
    "users" : [ {
      "name" : "Bob",
      "_links" : {
        "self" : {
          "href" : "http://localhost:4200/api/users/1"
        },
        "user" : {
          "href" : "http://localhost:4200/api/users/1"
        }
      }
    }, {
      "name" : "Joe",
      "_links" : {
        "self" : {
          "href" : "http://localhost:4200/api/users/2"
        },
        "user" : {
          "href" : "http://localhost:4200/api/users/2"
        }
      }
    } ]
  },
  "_links" : {
    "self" : {
      "href" : "http://localhost:4200/api/users"
    },
    "profile" : {
      "href" : "http://localhost:4200/api/profile/users"
    },
    "search" …
Run Code Online (Sandbox Code Playgroud)

angular2-services angular

4
推荐指数
1
解决办法
2326
查看次数

Typescript,Angular 2 - 将Json解析为http中的对象

我有一个文件location.json,包含以下形式的json字符串:

{
  "locations": [
    {
      "id": 1,
      "places": [
        {
          "id": 1,
          "city": "A",
          "state": "AB"
        }
      ]
    }
}
Run Code Online (Sandbox Code Playgroud)

我创建了表单的类:

export class Location{
       constructor(public id: number,
        public places: Place[],
     }

export class Place {
        constructor(
        public id: number, 
        public city: string,
        public state: string
} 
Run Code Online (Sandbox Code Playgroud)

如何将json字符串解析为object?我做了这样的事情:

...
export class DashboardComponent {

  locations: Locations[];

  constructor(private locationService:LocationService) {
    this.getLocations() 
  }

  getLocations(){
      this.locationService.get('assets/location.json')
      .subscribe(res => this.location = res);
  }
Run Code Online (Sandbox Code Playgroud)

parsing json typescript angular2-services angular

4
推荐指数
2
解决办法
7712
查看次数

如何以角度2获取YYYY-MM-DD格式的日期

我希望以下列格式获取日期:YYYY-MM-DD.

我基于这个问题在Angular2中写了一个日期服务: 如何在JavaScript中获取当前日期?.

我想检查它是否是正确的实现,或者是否有更好的方法来实现目标.

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

@Injectable()
export class DateService {
private currentDate = new Date();

    getCurrentDateInApiFormat(): string{
        let day:any = this.currentDate.getDate();
        let month:any = this.currentDate.getMonth() + 1;
        let year:any = this.currentDate.getFullYear();
        let dateInApiFormat: string;

        if(day<10){
           day = '0' + day.toString();
        }
        if(month<10){
            month = '0' + month.toString();
        }
        dateInApiFormat = day + '-' + month + '-' + year.toString();
        return dateInApiFormat;
    }
}
Run Code Online (Sandbox Code Playgroud)

javascript date angular2-services angular

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

如何在使用类似路径时将数据推入Angular 2中的数组

到目前为止,我还没有找到一个如何在Angular 2中将数据推送到数组的简单示例.在AngularJs中它很容易(示例),但我在Angular 2中正在努力,可能是因为我使用的是路由器我不知道如何配置它(我跟随角度英雄的例子).

我想做什么,整个解决方案:

app.module.ts:

import { NgModule } from "@angular/core";
import { BrowserModule } from "@angular/platform-browser";
import { FormsModule } from '@angular/forms';
import { RouterModule } from '@angular/router';
import { LocationStrategy, HashLocationStrategy } from '@angular/common';
import { HttpModule } from '@angular/http';
import { ProductsService } from '../services/ProductsService';


import { AppComponent } from "./components/app";
import { Products } from "./components/products";

@NgModule({
    imports: [
        BrowserModule,
        FormsModule,
        HttpModule,
        RouterModule.forRoot([
            {
                path: 'products/:class_id/:type_id',
                component: Products
            }
        ], { useHash: …
Run Code Online (Sandbox Code Playgroud)

angular2-routing angular2-services angular

4
推荐指数
1
解决办法
643
查看次数

Angular 2/4 FileReader服务

我试图创建Angular 2/4服务,可能上传文件.我找不到任何资源的解决方案,所以我可能想问你们.所以这个想法在Component的某个地方有输入字段,其中type = file.它有指令(change)="uploadFile($ event)".在组件.ts文件中:

uploadFile(event) {
   this.images.push(this.uploadImgService.uploadImage(event));
}
Run Code Online (Sandbox Code Playgroud)

UploadImgService看起来像这样:

private img: string;

uploadImage(e) {
  const file = e.target.files[0];
  const pattern = /image-*/;

  if (!file.type.match(pattern)) {
    alert('You are trying to upload not Image. Please choose image.');
    return;
  }
  const reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onloadend = () => {
    this.img = reader.result;
  };

  return this.img;
}
Run Code Online (Sandbox Code Playgroud)

所以,我知道操作是异步的,但我无法弄清楚如何将它包装起来,直到img加载为止.我认为这是技能缺乏的结果:(当我将这些代码发布到组件中它肯定有效,但我的想法是提供服务.而且,我只是Angular的初学者.所以,如果有更好的方法重新定义这个想法我很高兴收到你的来信.谢谢!

javascript filereader angular2-services angular

4
推荐指数
1
解决办法
2694
查看次数