0
votes

I am brand new to the Angular world. I have a simple application simply queries a database then displays the data in a table. This is the code from the service to run the query (db.service.ts):

query(): Observable<printerResults[]>{
return this.http.get<printerResults[]>(this.dataURL);
};

The call from my component (Printer-component.ts:

results: printerResults[];

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

getData(): void {

this.TestService.query()
.subscribe((res: printerResults[]) => {this.results = res}, err => 
console.log("error"));
}

And my class declaration (Results.ts):

export class printerResults {
 Cell: string;
 Plant: string;
 PrinterDPI: number;
 PrinterName: string;
 PrinterType: string;
}

If I put a console.log in the subscribe like:

    .subscribe(res => console.log(res), err => 
    console.log("error"));

It shows the full object. But when i try to use it on the html side, I get [object Object]. Any help would be appreciated.

2
You have to print each property of res object. Try doing this.res = res and then in your template do the following {{res | json}} - JSingh
Your api has the same names of variables that your model? - Abel Valdez

2 Answers

0
votes

Parse the json in the pipe, so the subscription will have an object coming into it, not a json string.

results: printerResults[];

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

getData(): void {

this.TestService.query()
.map( _res => JSON.parse(_res) )
.map( _res => _res.map( _raw => PrinterResults.initFromJsonRaw( _raw ) ) )
.subscribe((res: printerResults[]) => {this.results = res}, err => 
console.log("error"));
}

PrinterResults

class PrinterResults...
    public static initFromJsonRaw(_object) : PrinterResults {
            let ret = new PrinterResults();

            ret.PrinterName = _object.name;
            ret.PrinterDPI  = _object.dpi;

            return ret;
    }
}

Then in the template, just interpolate the result data. ngFor loop it, because, it seems to be an array in your code.

.html

<ng-container *ngFor="let result of results">
    <p>Name: {{ result.PrinterName }}</p>
    <p>DPI: {{ result.PrinterDPI }}</p>
</ng-container>
0
votes

May be Your api and your model(Results.ts) have different variables name so model is not bind....

  this.TestService.query()
   .subscribe((res: printerResults[]) =>{
          for (let i = 0; i < res.length; i++) {
            this.results.push(new printerResults(res[i]));
        }
     });

try this way to get value in results variable.