简体   繁体   English

订阅返回未定义

[英]Subscribe returning Undefined

I am brand new to the Angular world. 我是Angular世界的新手。 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): 这是服务中运行查询的代码(db.service.ts):

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

The call from my component (Printer-component.ts: 来自我的组件(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): 和我的类声明(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: 如果我将console.log放在订阅中,例如:

    .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]. 但是,当我尝试在html端使用它时,我得到了[object Object]。 Any help would be appreciated. 任何帮助,将不胜感激。

Parse the json in the pipe, so the subscription will have an object coming into it, not a json string. 解析管道中的json,因此订阅中将包含一个对象,而不是json字符串。

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 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. ngFor循环它,因为,它似乎是代码中的数组。

.html html的

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

May be Your api and your model(Results.ts) have different variables name so model is not bind.... 可能是您的api和您的模型(Results.ts)具有不同的变量名称,因此未绑定模型。

  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. 尝试这种方式来获取结果变量的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM