首页 > 解决方案 > 无法将 url 读取为 JSON 数据

问题描述

我有这个 JSON 数据,我正在使用 Angular 将其输出到 html 文件。我使用一个服务来获取 JSON 数据并使用一个组件来创建模板。使用模板后,我只得到 id 值和 name 值,而不是 url 值。

JSON:

{
 "A":1,
 "B":[
  {
   "id":1, 
   "name":"One", 
   "url":"http://myapp/rootpath/first"
  },
  {
   "id":2, 
   "name":"two", 
   "url":"http://myapp/rootpath/second"
  }
 ]
}

我将 JSON 数据带到组件中的 postArray 变量并将其传递给 html 文件。

search.service.ts:

import { Injectable } from '@angular/core';
import {Http,Response} from "@angular/http";
import { Observable } from "rxjs";
import "rxjs/Rx";
import {JsoncallItem} from "./jsoncall-item";

@Injectable({
  providedIn: 'root'
})
export class ApiService {

  private postsURL ="http://myapp/items";

  constructor(private http: Http ) {}
 getPosts(): Observable<JsoncallItem[]>{
    return this.http
     .get(this.postsURL)
     .map((response: Response)=> {
       return <JsoncallItem[]>response.json();
     })
     .catch(this.handleError);
 }

 private handleError(error: Response) {
   return Observable.throw(error.statusText);
 }
}

search.component.ts

import { Component, OnInit } from '@angular/core';
import { ApiService } from "./../search.service";
import { JsoncallItem } from "./../jsoncall-item";
import { error } from 'util';
import { SearchtermPipe } from './../searchterm.pipe';

@Component({
  selector: 'app-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.css']
})
export class SearchComponent implements OnInit {

    title = 'app';

    _postsArray: JsoncallItem[];

  constructor(private apiSerivce: ApiService){}

  getPosts(): void {
    this.apiSerivce.getPosts().
    subscribe(
       resultArray => this._postsArray = resultArray
       )
       //error => console.log("Error :: " + error ))
  }
  ngOnInit(): void{
    this.getPosts();
  }
}

search.component.html:

<div class="container">
    <ul>
        <li *ngFor="let post of _postsArray | searchterm: value">
            <a href="" id="allitem">{{post.id}}, {{post.name}}, {{post.url}}</a>
            <hr>
        </li>

    </ul>
</div>

输出显示每个数据的 id 和名称,但不显示 url。这里可能有什么问题?

标签: htmljsonangular

解决方案


推荐阅读