8

Hi I am creating an Angular 2 app. It seems like the service is not getting injected correctly as I don't see the page showing any results. I have set the risk-list.component.html as the startup page. Could somebody tell me what the problem is ?
I have uploaded the code in a plunker as well

app.module.ts

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent }  from './app.component';
import { RiskListComponent } from './components/risks/risk-list.component';

@NgModule({
    imports: [BrowserModule],
    declarations: [AppComponent, RiskListComponent],
    bootstrap: [AppComponent]
})
export class AppModule { }  

app.component.ts

import { Component } from '@angular/core';
import { DataTable, Column } from 'primeng/primeng';
import { Router } from  '@angular/router';
import {  Routes, RouterModule } from  '@angular/router';
import { WelcomeComponent } from  './components/home/welcome.component';
import { RiskListComponent } from './components/risks/risk-list.component';
import { RiskDetailsComponent } from './components/risks/risk-detail.component';
import { ModuleWithProviders } from '@angular/core';
import './rxjs-operators';


import { RiskService } from './components/risks/risk.service';

@Component({
    selector: 'my-app',
    template: `
    <div>
        <h1>{{pageTitle}}</h1>
          <rm-risks> </rm-risks> 
    </div>
    <div>
      <router-outlet>  </router-outlet>
    </div>
     ` 
    //,
    //directives: [RiskListComponent, DataTable, Column],

})

export class AppComponent {
    pageTitle: string = 'Test UK Trader';
}

const appRoutes: Routes = [
    { path: '/welcome', component: WelcomeComponent },
    { path: '/risks', component: RiskListComponent },
    { path: '/riskdetails', component: RiskDetailsComponent }
];

main.ts

  import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
    import { RiskService } from './components/risks/risk.service';
    import { HttpModule, JsonpModule } from  '@angular/http';
    import './rxjs-operators';
    import { enableProdMode } from '@angular/core';
    import { AppModule } from './app.module';


    const platform = platformBrowserDynamic();

    platform.bootstrapModule(AppModule, [HttpModule, JsonpModule, RiskService]).catch(err => console.error(err));

risk-list.component.ts

import { Component, OnInit } from '@angular/core';
import { IRisk } from './risk';
import { RiskService } from './risk.service';
import { DataTable, Column } from 'primeng/primeng';
import {Header} from 'primeng/primeng';
import {Footer} from 'primeng/primeng';
import {Paginator} from 'primeng/primeng';


@Component({
    selector: 'rm-risks',
    //directives: [DataTable, Column, Header, Footer, Paginator],
    templateUrl: '/app/components/risks/risk-list.component.html',
    providers: [RiskService]
    })

export class RiskListComponent  {
    pageTitle: string = 'Risk List';
    errorMessage: string;
    risks: IRisk[];

    constructor(private _riskService: RiskService) {

        this.risks = this._riskService.getRisks();
    }


};

risk-list.component.html

<h3 class="first">{{pageTitle}}</h3>
<!--[rows]="5" [paginator]="true" [pageLinks]="2" [rowsPerPageOptions]="[5,10,20]"-->
<!--<p-paginator rows="10" totalRecords="100" pageLinkSize="3"></p-paginator>-->
<p-dataTable [value]="risks" [paginator]="true" rows="5" totalRecords="100" pageLinkSize="3" [rowsPerPageOptions]="[5,10,20]"  [sortMode]="multiple" sortField="inceptionDate" [sortOrder]="1" >
    <header>List of Risks</header>


        <!--<footer>Choose from the list.</footer>-->
        <p-column field="reference" header="Reference (contains)" [filter]="true" sortable="true"></p-column>
        <p-column field="insuredName" header="Insured Name (contains)" [filter]="true" sortable="true"></p-column>
        <p-column field="inceptionDate" header="Inception Date (contains)" [filter]="true" sortable="true"></p-column>
        <p-column field="riskType" header="Risk Type (contains)" [filter]="true" sortable="true"></p-column>
        <p-column field="status" header="Status (contains)" [filter]="true" sortable="true"></p-column>
        <p-column field="grossPremium" header="Gross Premium (contains)" [filter]="true" sortable="true"></p-column>
        <p-column field="allocatedTo" header="Allocated To (contains)" [filter]="true" sortable="true"></p-column>
        <p-column field="allocatedCompany" header="Allocated Company (contains)" [filter]="true" sortable="true"></p-column>

</p-dataTable>

riskservice

import { Injectable } from '@angular/core';
import { IRisk } from './risk';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/from';


@Injectable()
export class RiskService {
    //private _riskUrl = '/api/risks/risks.json';
    //constructor(private _http: Http) { }

    //getRisks(): Observable<IRisk[]> {
    //    return this._http.get(this._riskUrl)
    //        .map((response: Response) => <IRisk[]>response.json())
    //        .catch(this.handleError);
   // }

    //private handleError(error: Response) {
    //}
//}

    getRisks(): IRisk[] {
        return [

            {
                "riskId": 1,
                "reference": "HISC9308336",
                "insuredName": "SA 84161",
                "inceptionDate": "March 19, 2016",
                "riskType": "Quote",
                "status": "Indication",
                "grossPremium": 100,
                "allocatedTo": "Broker User",
                "allocatedCompany": "Broker"
            },
            {
                "riskId": 2,
                "reference": "HISC9308340",
                "insuredName": "Upper Loi",
                "inceptionDate": "April 25, 2016",
                "riskType": "Quote",
                "status": "Indication",
                "grossPremium": 312.22,
                "allocatedTo": "Andy Marples",
                "allocatedCompany": "Broker"
            }
        ];
    }
}

Application Structure

enter image description here

Logan H
  • 3,383
  • 2
  • 33
  • 50
Tom
  • 8,175
  • 41
  • 136
  • 267

3 Answers3

1

This code fetches the risks, but doesn't do anything with it

getRisks(): void {
    this._riskService.getRisks();
}

I assume it should be

getRisks(): void {
    this.risks = this._riskService.getRisks();
}

and I assume ngOnInit() should be

ngOnInit(): void {                                                                                                                  
  //  this._riskService.getRisks();
  this.getRisks();
}
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • getRisks(): void { this._riskService.getRisks().then(risks => this.risks = risks); } ngOnInit(): void { this.getRisks(); } – Tom Sep 28 '16 at 13:17
  • Can you provide a running Plunker. The "new" button in the Plunker editor provides an up-to-date Angular2 TS template. – Günter Zöchbauer Sep 28 '16 at 13:20
  • i had already previously uploaded the code in plunker. I have updated it with the changes you suggested. However when i click the run button the index.html page gets executed. How do I set the risk-list.component.html page as startup and execute it in plunker. Running the code locally in visual studio doesn't show anything. http://plnkr.co/edit/y3tv8gdnXtGSg8Wl6F8H?p=preview – Tom Sep 28 '16 at 13:33
  • To me it doesn't look like you used a Plunker template. Seems you copied your local system.js config which doesn't work in Plunker. You should start from a working Plunker Angular2 TS template. – Günter Zöchbauer Sep 28 '16 at 13:35
  • Please use a plunk template as Gunter says. I tried to reproduce your code in plunker but I have problems with templateUrl path and It's taking me so much time trying to reproduce your isue. Green button New -> angular -> chooseVersioYouWant – Shil Nevado Sep 28 '16 at 13:40
  • Hi Shil,Gunter, I had clicked on New button and chosen an Angular template. I then clicked on new files and then added the code from my local to the plunker project. Will removing the system.js help – Tom Sep 28 '16 at 13:47
  • I have renamed the system.js file to config.js and copied contents from an existing plunker template. Let me know if that helps. The version I chose was Angular 2 Typescript – Tom Sep 28 '16 at 13:51
  • http://plnkr.co/edit/nlnK1mTtgoyaOif3ZbQ1?p=preview shows the risks as JSON – Günter Zöchbauer Sep 28 '16 at 14:03
  • You must **not** prefix paths in route configs with `/`. – Günter Zöchbauer Sep 28 '16 at 14:03
  • Hi Gunter, I am still trying to understand your solution. Is it only the route.config that you have modified. As, when I make the changes to my local route.config, it doesnt work. I am using visual studio 2015. When I select risk-list.component as start up page or type url for e.g http://localhost:3622/risks, shows me blank page with just the heading – Tom Sep 28 '16 at 14:42
  • I don't know about Visual Studio setup for Angular2. You might try with `HashLocationStrategy` first http://stackoverflow.com/questions/36861628/location-and-hashlocationstrategy-stopped-working-in-beta-16 It is possible that VS2015 doesn't support the default HTML5 pushState by default. – Günter Zöchbauer Sep 28 '16 at 14:46
  • I have tried using the hashlocation strategy in my appmodule but no luck. Somebody with knowledge of configuring angular in visual studio will be of help – Tom Sep 28 '16 at 17:24
  • When using an `ngModule` the service instantiation should go in there https://angular.io/docs/ts/latest/guide/ngmodule.html#!#providers. The plunk http://plnkr.co/edit/oQ0PQAFsKPLQXTmJsktY?p=preview – Logan H Oct 04 '16 at 17:15
  • Where you provide a service depends on what scope you want the service to have. If you add it to `@NgModule(providers: [])` the the whole application shares one instance (when the module is not lazy loaded), if you add it to `@Component(providers: [])` then the component and it's children share one instance. http://plnkr.co/edit/yO27bu3PhcwQYJdrRXl5?p=preview. – Günter Zöchbauer Oct 04 '16 at 17:29
  • Sure but if he is modifying this list and then using the modified list anywhere else in the application, wouldn't he want it at the application level? – Logan H Oct 04 '16 at 17:35
  • Sure, but that wasn't explicitly stated and it wasn't the cause for the error. – Günter Zöchbauer Oct 04 '16 at 17:38
  • Sure, sure, that makes sense. Getting side tracked – Logan H Oct 04 '16 at 17:40
1

You have to teach the injector how to make a Risk Service. You do this by registering a RiskService provider. You have to do this inapp.component.ts.

In your component under the template add provider [RiskService]

Here is the explanatioin from the angualr 2 site.

mfcastro
  • 35
  • 6
0

You have to include your service into the NgModule

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent }  from './app.component';
import { RiskListComponent } from './components/risks/risk-list.component';
import { RiskService } from './risk.service';

@NgModule({
    imports: [BrowserModule],
    declarations: [AppComponent, RiskListComponent],
    bootstrap: [AppComponent],
    providers: [RiskService]
})
export class AppModule { }

The more logic implementation for me in your code, is use that service as singleton. So you don't need to include it on the Component declaration as a provider. Only in the constructor.

quindimildev
  • 1,280
  • 8
  • 21