简体   繁体   中英

http observable<any> - Angular 4

I need to display the data on html that I get from web service. I am able to see the data in a format that I want, but I can't display properly on html. I think -any- in http.get is the problem. I can read data in console without -any- but it works fine with . When it works with it, it still does not print in html properly. Can anyone provide advice on this?

html

<div>{{this.res}}</div>

app.component.ts

import { Component, OnInit } from '@angular/core';
//import { IMovie } from './movie';
import { AppService } from './app.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  res: any[] ;
  errorMessage: string;

  constructor(private _appService: AppService) { }

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

  getData(): void {
    this._appService.getData()
      .subscribe(
      (res: any []) => this.res = res,
      (error: any) => this.errorMessage = <any>error);

  }
}

app.service.ts :

Injectable()
export class AppService {
private urlNorth = '';
constructor(private http: HttpClient) { }

    getData(): Observable<any> {

    const headers = new HttpHeaders();
    headers.set('Content-Type', 'text/sml');
    headers.set('Accept', 'text/xml');
    headers.set('Content-Type', 'text/xml');

    return this.http.get<any>(this.urlNorth,{responseType:'text', headers: headers})
        .do(data => {
            // console.log(data)
            var dataParsed = data.replace('<string xmlns="service">', '').replace('</string>', '').replace(/&lt;/g, '<').replace(/&gt;/g, '>');
            // console.log(dataParsed);
            parseString(dataParsed, (err, res) => {
                if (err) {
                    return console.dir('invalid XML');
                }
                else {
                    console.log(res);
                    console.log(res.NewDataSet.Table[0].DataPointName[0]);
                }
            })

        })

        .catch(this.handleError);
}

**data in console w/o any **

1

{{this.res}} in html 在此处输入图片说明

I'm pretty sure you don't have to put any at this line in app.service.ts

return this.http.get<any>(this.urlNorth,{responseType:'text', headers: headers})

because get method expects 0 type arguments.

Type any is not the problem. It's just TypeScript annotation to organise your code. The problem is you are refering to the res in inline template as this.res , but you should just res . However it won't work as you think. Looking at your data structure You will have to iterate throught this data due to Table is an array. Additionaly I Highly suggest to always represnt your data as class

export class Apps {
   public Table: Array<any>; //here should be another type instead of "any"
   /* rest of data if any */
}

Back to your question you should have in your html file <div>{{res}}</div> but that's just print your object as string if I good remember. So to properly access your data you should iterate through table using *ngFor

<div *ngFor="let el of res.NewDataSet.Table">
    <span>{{el.BackColor}}</span>
    <!-- all other data -->
</div>

It looks as though the data is coming back. I'll answer your initial question first (since you added a few issues in comments):

My guess is when you get data back, it's not showing because it's HTML, and angular doesn't like injecting html.

Add this to your TS:

import { DomSanitizer, SafeHtml } from '@angular/platform-browser';

res[]: safeHTML;

And change your html to this:

<div [innerHTML]="res"></div>

As mentioned in a previous answer, this is a solution for a single return of res, not an array of different htmls. If it's an array, you'll have to handle it accordingly. for instance:

<ng-container *ngFor="let r of res">
   <div [innerHTML]="r">
</ng-container>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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