[英]http observable<any> - Angular 4
我需要在從Web服務獲取的html上顯示數據。 我能夠以所需的格式查看數據,但是無法在html上正確顯示。 我認為http.get中的-any-是問題所在。 我可以在沒有-any-的情況下在控制台中讀取數據,但可以正常使用。 當與它一起使用時,它仍然不能正確地以html打印。 有人可以提供建議嗎?
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(/</g, '<').replace(/>/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);
}
**控制台中的數據不包含任何**
我很確定您不必在app.service.ts的這一行添加任何內容
return this.http.get<any>(this.urlNorth,{responseType:'text', headers: headers})
因為get方法需要0個類型參數。
鍵入any
不是問題。 它只是用於組織代碼的TypeScript
批注。 問題是您將內聯模板中的res
this.res
為this.res
,但是您應該只使用res
。 但是,它不會像您所想的那樣起作用。 查看您的數據結構由於Table
是一個數組,您將不得不遍歷此數據。 我強烈建議您始終將您的數據表示為class
export class Apps {
public Table: Array<any>; //here should be another type instead of "any"
/* rest of data if any */
}
回到您的問題,您應該在HTML文件<div>{{res}}</div>
但是如果我記得的話,那只是將您的對象打印為字符串。 因此,要正確訪問數據,您應該使用*ngFor
遍歷表
<div *ngFor="let el of res.NewDataSet.Table">
<span>{{el.BackColor}}</span>
<!-- all other data -->
</div>
好像數據又回來了。 我將首先回答您的第一個問題(因為您在評論中添加了一些問題):
我的猜測是,當您取回數據時,它不會顯示,因為它是HTML,並且angular不喜歡注入html。
將此添加到您的TS:
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
res[]: safeHTML;
並將您的html更改為此:
<div [innerHTML]="res"></div>
如上一個答案中所述,這是單返回res而不是不同html數組的解決方案。 如果是數組,則必須相應地處理它。 例如:
<ng-container *ngFor="let r of res">
<div [innerHTML]="r">
</ng-container>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.