带有observable的Angular调用API未显示数据

时间:2017-11-09 02:45:03

标签: json angular observable

我已经实现了一个angular 5应用程序来从Web API中提取数据。我正在使用一个observable来获取json。来自API的Json看起来像这样:

{
 "Job": [
 {
  "Title": "Solution Architect",
  "Summary": "Solution Architect",
  "Salary": {
    "MinValue": "100",
    "MaxValue": "100",
    "Text": "",
    "Period": "HourlyRate"
  },      
  "Reference": "234483_1",
},
{
  "Title": "Senior Business Analyst – eCommerce ",
  "Summary": "Senior Business Analyst...",
  "Salary": {
    "MinValue": "80",
    "MaxValue": "100",
    "Text": "",
    "Period": "HourlyRate"
  },      
  "Reference": "234874_1",
}
],
"Advertiser": "Resourcing",
"Source": "Wiz"
}

我创建的服务如下:

  ....
  @Injectable()
  export class AdvDataService {
  private _getAddsUrl = 'https://xx.xxxx.com/v1/adverts/www111';

 constructor(private _http: Http) { }

 getAdvForClient(): Observable<IAdv> {
   return this._http.get(this._getAddsUrl)
    .map((response: Response) => <IAdv>response.json()) 
    .do(data => console.log('All:' + data))
    .catch(this.handleError);
  }

该组件看起来像:

....
export class HomeComponent implements OnInit {

constructor(private _sdvDataService: AdvDataService) { }

private loadAdverts: IAdv;
private errorMesage: string;

ngOnInit() {
this.errorMesage = "";
this._sdvDataService.getAdvForClient()
    .subscribe(adv => {
        this.loadAdverts = adv;
       console.log ("here:"  + this.loadAdverts)
    }, error => {
        this.errorMesage = <any>error;        
    });
 }

}

我有一个简单的界面:

export interface IAdv {

Advertiser: string,
Source:string

}

和我的HTML:

<div  *ngIf="loadAdverts" >
<div class="row justify-content-center">
  <div class="card" style="width: 20rem;">
    <div class="card-body">
      <h4 class="card-title">here: {{loadAdverts.Advertiser}}</h4>
      <h6 class="card-subtitle mb-2 text-muted">{{loadAdverts.source}} </h6>
      <p class="card-text">{{loadAdverts.source}}</p> 
      <a href="#" class="card-link">Card link</a>
      <a href="#" class="card-link">Another link</a>
    </div>
  </div>
</div>

我可以在组件和服务中的console.log中看到控制台中显示的json,但视图中会显示任何数据。

我很感激你的帮助吗?

更新:来自服务器的json似乎是一个json字符串。所以它没有在observable中被解析。我不得不在suscriber中使用json.parse。如何使用suscriber自动将json字符串解析为json对象?

2 个答案:

答案 0 :(得分:0)

您的loadAdverts是私有变量,因此无法在模板中访问。

要么像这样公开。

public loadAdverts:IAdv;

或使用getter和setter。

private _loadAdverts:IAdv;
   ....

get loadAdverts(): IAdv {
 return this._loadAdverts;
}

set loadAdverts(_ad: IAdv) {
 this._loadAdverts = _ad;
}

   ....

答案 1 :(得分:0)

正如我们所看到的,您正在接收包含数组的对象Job,因此您应该从对象中提取该数组:

getAdvForClient(): Observable<IAdv> {
  return this._http.get(this._getAddsUrl)
    .map((response: Response) => <IAdv>response.json().Job) // here!
    .do(data => console.log('All:' + data))
    .catch(this.handleError);
}

另外,既然你得到了一个数组,你可能希望在你的模板中迭代它:

<div *ngFor="let adv of loadAdverts">
  <p>{{adv.Source}}</p>
  <!-- more code here -->
</div>

另请注意,这是区分大小写的,您在模板中使用source作为属性名称而不是Source