使用Angular 4获取json文档时出现问题?

时间:2017-04-28 19:35:14

标签: angular

我有以下Angular示例从https://raw.githubusercontent.com/angular/angular/master/bower.json获取json文档,并在<h1>{{title}}</h1>

等模板中显示response.toString()
import {Component} from "@angular/core";
import {Http} from "@angular/http";
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app works!';

  // url = 'http://s331998788.online.de:5080/dict.json';
  url = 'https://raw.githubusercontent.com/angular/angular/master/bower.json';

  constructor(http: Http) {
    let params: URLSearchParams = new URLSearchParams();
    http.get(this.url).subscribe(t => this.title = t.toString());
  }

}

t.toString()Response with status: 200 OK for URL: https://raw.githubusercontent.com/angular/angular/master/bower.json返回{{title}}

如果我得到了网址http://s331998788.online.de:5080/dict.jsont.toString()似乎没有向{{title}}返回任何内容,模板只显示app works!

这个json文档出了什么问题?

在我看来,相关的差异是工作页面有Access-Control-Allow-Origin: *而另一个没有。如果这是问题的根源,我如何告诉http获取这些文件?

curl -i询问标题信息,我们得到以下内容:

$ curl -i 'http://s331998788.online.de:5080/dict.json'
HTTP/1.1 200 OK
Server: Zope/(2.13.21, python 2.7.5, linux2) ZServer/1.1
Date: Fri, 28 Apr 2017 23:01:32 GMT
Last-Modified: Fri, 28 Apr 2017 23:01:23 GMT
Content-Length: 46
Content-Type: application/json
Accept-Ranges: bytes

  {
    "name": "John",
    "age": 21
  }


$ curl -i 'https://raw.githubusercontent.com/angular/angular/master/bower.json'
HTTP/1.1 200 OK
Content-Security-Policy: default-src 'none'; style-src 'unsafe-inline'
Strict-Transport-Security: max-age=31536000
X-Content-Type-Options: nosniff
X-Frame-Options: deny
X-XSS-Protection: 1; mode=block
ETag: "007371a434d2486e54fb403ff912ec202322d603"
Content-Type: text/plain; charset=utf-8
Cache-Control: max-age=300
X-Geo-Block-List:
X-GitHub-Request-Id: 2C5E:674E:431187:459555:5903C9F0
Content-Length: 89
Accept-Ranges: bytes
Date: Fri, 28 Apr 2017 23:02:09 GMT
Via: 1.1 varnish
Connection: keep-alive
X-Served-By: cache-hhn1523-HHN
X-Cache: MISS
X-Cache-Hits: 0
X-Timer: S1493420529.409818,VS0,VE110
Vary: Authorization,Accept-Encoding
Access-Control-Allow-Origin: *
X-Fastly-Request-ID: 9270c2ab79c2d179ec005957794044dc1796841b
Expires: Fri, 28 Apr 2017 23:07:09 GMT
Source-Age: 0

{
  "name": "angular",
  "dependencies": {
    "polymer": "Polymer/polymer#^1.6.0"
  }
}

1 个答案:

答案 0 :(得分:0)

http.get(this.url).subscribe(t => this.title = t.toString()); 方法返回一个响应对象(如评论中所说的wannadream)。

t.text()

这显示了响应对象的字符串表示形式,如果要查看json,则必须使用t.json()(获取正文的原始文本)或http.get(this.url).subscribe(t => this.title = t.toString(), error => console.error(error)); (解析原始文本)将文本写入对象)。

您应该添加错误订阅,以了解您没有标题内容的原因:

{{1}}