user6879896
user6879896

Reputation:

Angular2: How to put return service value into private variable object?

I am creating an Accounting System UI and using angular2 as my framework.

My app is working except for assigning the service value into private var. I created a service to make it more dynamic.

So, here's my Service

/* formdata.ts */

export class Formdata {
    viewBy: string;
    companyUnit: string;
    financialYear: string;
    clients: string;
}

/* mocked-form */

import { Formdata } from './formdata'

export const FORMDATA: Formdata[] = [
    {
        viewBy: 'Daniela Oraa',
        companyUnit: 'BIR - Legazpi',
        financialYear: '2016',
        clients: 'Dummy Text 1'
    }
];

/* form.service.ts */

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

import { Formdata } from './formdata';
import { FORMDATA } from './mocked-form';

@Injectable()
export class FormService {
  getData(): Promise<Formdata[]> {
    return Promise.resolve(FORMDATA);
  }
}

Injecting Service into Component

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

import { Formdata } from '../formdata';
import { FormService } from '../form.service';

@Component({
  templateUrl: 'app/html-templates/clientdata_balance.html',
  styleUrls: ['css/templates.css'],
  providers: [ FormService ]
})

export class BalanceComponent implements OnInit {
    formData: Formdata[];

    constructor(private formService: FormService){}

    getData(): void {
        this.formService.getData().then(formData => this.formData = formData);
    }

    ngOnInit(): void {
        this.getData();
    }

    private data = this.formService.getData().then(formData => this.formData = formData);

    search_data(data){
        console.log(data);
    }
}

If you check the private data in component. I tried to get the data in the service. Unfortunately, no luck.

Basically, it will be a value of inputs and selecboxes.

So, here's my form

<form>
  <label class="input-group">
    <p>View By</p>
    <select [(ngModel)]="data.viewBy" name="viewBy">
      <option>Daniela Oraa</option>
      <option>Lovely Laparan</option>
      <option>Justin Bibo</option>
    </select>
  </label>
  <label class="input-group">
    <p>Company Unit</p>
    <select [(ngModel)]="data.companyUnit" name="companyUnit">
      <option>Nusa</option>
      <option>Bumi</option>
    </select>
  </label>
  <label class="input-group">
    <p>Financial Year</p>
    <select [(ngModel)]="data.financialYear" name="financialYear">
      <option>2016</option>
      <option>2004</option>
      <option>1945</option>
      <option>1897</option>
    </select>
  </label>
  <label class="input-group">
    <p>Clients</p>
    <select [(ngModel)]="data.clients" name="clients">
      <option>Dummy Text 1</option>
      <option>Dummy Text 2</option>
      <option>Dummy Text 3</option>
    </select>
  </label>
  <label class="input-group">
    <p>Date From</p>
    <input type="date" [(ngModel)]="data.dateFrom" name="dateFrom"/>
  </label>
  <label class="input-group">
    <p>Date To</p>
    <input type="date" [(ngModel)]="data.dateTo" name="dateTo"/>
  </label>
  <button type="button" (click)="search_data(data)">Search</button>
</form>

The logic I can think to put a value in ngModel data object is:

private data = {
  viewBy: 'Daniela Oraa',
  ...
}

I also tried this eventhough it I knew that it won't work.

private data = formData;

The second way is to inject value inside the element.

<form *ngFor="let fdata of formData">
    <select [(ngModel)]="data.viewBy" name="viewBy" [ngValue]="fdata.viewBy"> 
    // this method fail but I can get fdata.viewBy value

    ...

I tried all that I can think of. And none of them work. So, I decided to ask it here in SO.

Any help would mean so much to me. Thanks.

Upvotes: 1

Views: 1600

Answers (2)

hdotluna
hdotluna

Reputation: 5732

Explanation inside the code.

In your component:

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

import { Formdata } from '../formdata';
import { FormService } from '../form.service';

@Component({
  templateUrl: 'app/html-templates/clientdata_balance.html',
  styleUrls: ['css/templates.css'],
  providers: [ FormService ]
})

export class BalanceComponent implements OnInit {
    formData: Formdata[];
    private data = {}; // prevents error property undefined

    constructor(private formService: FormService){}

    // no need to reference a function (getData) because you will use it right away

    ngOnInit(): void {
        this.formService.getData().then(value => {
            // getData() from form.service.ts

            for(let i in value[0]) this.data[i] = value[0][i];
            /* Basically, this for ... in loop do the magic.
               Looping over the object

               It will be this.data[key] = value
               -- or -- for example

               this.data['viewBy'] = 'Sample 1';
               this.data['companyUnit'] = 'BIR';
               ...

            */
        })
    }

    search_data(data){
        console.log(data);
    }
}

Hope it works with you. Cheers!

Upvotes: 1

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657248

With this line

private data = this.formService.getData().then(formData => this.formData = formData);

the data (FORM_DATA from your service) is assigned to this.formData.

this.data only gets a reference to the promise.

Upvotes: 0

Related Questions