angular2: Supplied parameters do not match any sig

2019-07-26 05:26发布

问题:

push.component.ts

import { Component, OnInit } from '@angular/core';

import {PushResult}        from './dto/pushResult';
import {PushRequest}       from './dto/pushRequest';
import {PushService}       from './push.service';

@Component({
    // selector: 'push-comp',
    template:
      //   `<form (submit)="submitForm()">
      //   <input [(ngModel)]="element.name"/>
      //
      //   <button type="submit">Submit the form</button>
      // </form>
      // <br>
    `<button (click)="getHeroes()"> get </button> <button (click)="saveHeroes()"> push </button>`,
    // templateUrl: 'app/html/heroes.component.html',
    providers: [PushService]
})
export class PushComponent implements OnInit {
    pushResult:PushResult;
    // selectedHero:Hero;
    // addingHero = false;
    error:any;
    element:any;

    constructor(private pushService:PushService) {
        console.info("in PushComponent constructor()");

    }

    getHeroes() {
        this.pushService
            .doSomeGet();
            // .then(pushResult => this.pushResult = pushResult)
            // .catch(error => this.error = error);
    }


    saveHeroes() {
        var pushRequest: PushRequest = new PushRequest();
        // this.pushService.doSelectMessagesAttributesUrl2(pushRequest);
        this.pushService.doFeatureCreateNewMessageUrl(pushRequest);
        this.pushService.doFeatureSelectPushMessages(this.element);
        // .then(pushResult => this.pushResult = pushResult)
        // .catch(error => this.error = error);
    }





    ngOnInit() {
        console.info("in PushComponent ngOnInit()");
       //  this.getHeroes();
       //   this.saveHeroes();
    }

}

push.service.ts

import { Injectable }             from '@angular/core';
import {Http, Response, Headers}  from '@angular/http';

import 'rxjs/add/operator/toPromise';
import 'rxjs/Rx';
import { PushResult } from './dto/pushResult';
import {PushRequest} from './dto/pushRequest';
import {StringUtilsService} from "../shared/stringUtils.service";


@Injectable()
export class PushService {
    //private pushUrl = 'http://www.ynet.com';  // URL to web api
    //  private getUrl = '/app/eladb.json';  // URL to web api
    private getUrl = '/SupporTool/ShowConfig?id=4';  // URL to web api
    private selectMessagesAttributesUrl = '/SupporTool/Push/SelectMessagesAttributes';  // URL to web api
    private postMultiMap = '/SupporTool/Push/FeatureCreateNewMessage';  // URL to web api
    private postBoolean = '/SupporTool/Push/FeatureSelectPushMessages';  // URL to web api

    private stringUtilsService : StringUtilsService;

    constructor(private http: Http) {
        this.stringUtilsService = new StringUtilsService();
    }

    doSomeGet() {
        console.info("sending get request");


        let headers = new Headers({
            'Content-Type': 'application/xml'});


        this.http.get(this.getUrl, {headers: headers})
            .map(res => res.text())
            .subscribe(
                data => { console.info("next: "+data) },
                err => console.error(err)
            );
    }

    doSelectMessagesAttributesUrl2(pushRequest : PushRequest) {
        console.info("sending post request");

        let headers = new Headers({
            'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'});

        return this.http
            .post(this.selectMessagesAttributesUrl, "", {headers: headers})
            .map(res => res.json())
            .subscribe(
                data => { console.info("next: "); console.info(data) },
                err => console.error(err)
            );
    }


    doFeatureCreateNewMessageUrl(pushRequest : PushRequest) {
        console.info("sending post request");

        let headers = new Headers({
            'Content-Type': 'application/x-www-form-urlencoded'});

        var isLimit = true;

        return this.http
            .post(this.postBoolean, "#limit="+isLimit, {headers: headers})
            .map(res => res.json())
            .subscribe(
                data => { console.info("next: "); console.info(data) },
                err => console.error(err)
            );
    }

    doFeatureSelectPushMessages(element : any) {
        console.info("sending post request");

        let dict = {"limit":"true", "name":"foo"}


        let headers = new Headers({
            'Content-Type': 'application/x-www-form-urlencoded'});


        var params = {};
        params['push_input_internal_id'] = "1";
        params['b'] = "2";

        var formParamString = this.stringUtilsService.mapToFormParamsString(params);

        return this.http
            .post(this.postMultiMap, formParamString , {headers: headers})
            .map(res => res.json())
            .subscribe(
                data => { console.info("next: "); console.info(data) },
                err => console.error(err)
            );
    }

    private handleError(error: any) {
        console.error('An error occurred', error);
        // return Promise.reject(error.message || error);
    }
}

push.component.spec.ts

import { By }           from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { addProviders, async, inject } from '@angular/core/testing';
import { PushComponent } from './push.component';

describe('Component: Push', () => {
  it('should create an instance', () => {
    let component = new PushComponent();
    expect(component).toBeTruthy();
  });
});

app.routing.ts

import { ModuleWithProviders }  from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { PushComponent }      from './push/push.component';


const appRoutes: Routes = [
  { path: '', redirectTo: '/push', pathMatch: 'full' },
  { path: 'push',  component: PushComponent}
];

export const appRoutingProviders: any[] = [];

export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);

I read this post, but it used to work for me. So i cannt understand what i am missing.

and i get this error after npm start

Build error

The Broccoli Plugin: [BroccoliTypeScriptCompiler] failed with:
Error: Typescript found the following errors:
  /Users/eladb/WorkspaceQa/SupporTool/src/main/webapp/html/ng2/tmp/broccoli_type_script_compiler-input_base_path-2GTEvnc7.tmp/0/src/app/push/push.component.spec.ts (10, 21): Supplied parameters do not match any signature of call target.
    at BroccoliTypeScriptCompiler._doIncrementalBuild (/Users/eladb/WorkspaceQa/SupporTool/src/main/webapp/html/ng2/node_modules/angular-cli/lib/broccoli/broccoli-typescript.js:120:19)
    at BroccoliTypeScriptCompiler.build (/Users/eladb/WorkspaceQa/SupporTool/src/main/webapp/html/ng2/node_modules/angular-cli/lib/broccoli/broccoli-typescript.js:43:10)
    at /Users/eladb/WorkspaceQa/SupporTool/src/main/webapp/html/ng2/node_modules/angular-cli/node_modules/broccoli-caching-writer/index.js:152:21
    at lib$rsvp$$internal$$tryCatch (/Users/eladb/WorkspaceQa/SupporTool/src/main/webapp/html/ng2/node_modules/angular-cli/node_modules/rsvp/dist/rsvp.js:1036:16)
    at lib$rsvp$$internal$$invokeCallback (/Users/eladb/WorkspaceQa/SupporTool/src/main/webapp/html/ng2/node_modules/angular-cli/node_modules/rsvp/dist/rsvp.js:1048:17)
    at lib$rsvp$$internal$$publish (/Users/eladb/WorkspaceQa/SupporTool/src/main/webapp/html/ng2/node_modules/angular-cli/node_modules/rsvp/dist/rsvp.js:1019:11)
    at lib$rsvp$asap$$flush (/Users/eladb/WorkspaceQa/SupporTool/src/main/webapp/html/ng2/node_modules/angular-cli/node_modules/rsvp/dist/rsvp.js:1198:9)
    at _combinedTickCallback (internal/process/next_tick.js:67:7)
    at process._tickCallback (internal/process/next_tick.js:98:9)

回答1:

PushComponent expects a PushService instance as parameter

constructor(private pushService:PushService) {

but you don't provide one

new PushComponent(/* parameter value missing */);

If you create an instance yourself with new Xxx() then Angulars DI is not involved and no dependencies are passed. Only when Angulars DI itself creates PushComponent does it resolve and pass dependencies.

import {beforeEachProviders, it, describe, inject} from '@angular/core/testing';

describe('my code', () => {
  beforeEachProviders(() => [PushService, PushComponent]);

  it('does stuff', inject([PushComponent], (pushComponent) => {
    // actual test
  });
});

Don't expect to get a component injected. What you get this way is an instance of the components class (without any change detection running, nor lifecycle hooks being called, ...)

If you want a component, then you need to use TestBed. See also https://github.com/angular/angular/blob/master/CHANGELOG.md