Я пытался создать небольшой пример в Angular2. То, что я делаю, когда я нажимаю кнопку, это делает добраться до общественного апи и показать цитаты, но я не может, значение не показывает, и я получил ошибкуПолучить значения json в Http.get
Не удается прочитать свойство «цитирует» неопределенных в [{{quote.contents.quotes.quote}} в App @ 4: 20]
Мои Component.ts
import {Component, OnInit, Injectable} from 'angular2/core';
import {Http, HTTP_PROVIDERS, URLSearchParams} from 'angular2/http';
import 'rxjs/add/operator/map';
@Component({
selector: 'app',
template: `<ul>
<li (click)='myAlert()'> Helow World</li>
</ul>
<div>
<spam>{{quote.contents.quotes.quote}}</spam>
</div>`,
providers: [HTTP_PROVIDERS]
})
export class App {
public quote: Object;
public logError: string;
constructor(private http: Http){
this.quote = {};
}
myAlert(){
this.http.get("http://quotes.rest/qod.json").map(res => { return res.json()})
.subscribe(
data => this.quote = data,
err => this.logError(err),
() => console.log('Random Quote Complete')
);
}
}
My boot.ts
import {bootstrap} from 'angular2/platform/browser'
import {App} from './component'
import {HTTP_PROVIDERS} from 'angular2/http';
bootstrap(App, [HTTP_PROVIDERS]).catch(err => console.error(err));
Index.html
<html>
<head>
<title>Angular 2 QuickStart</title>
<!-- 1. Load libraries -->
<script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="node_modules/rxjs/bundles/Rx.js"></script>
<script src="node_modules/angular2/bundles/angular2.dev.js"></script>
<script src="https://code.angularjs.org/2.0.0-beta.1/http.js"></script>
<!-- 2. Configure SystemJS -->
<script>
System.config({
packages: {
app: {
format: 'register',
defaultExtension: 'js'
}
}
});
System.import('app/boot')
.then(null, console.error.bind(console));
</script>
</head>
<!-- 3. Display the application -->
<body>
<app>Loading...</app>
</body>
</html>
Как я получаю значения от сервиса подписки и поместить в мой шаблон?
Вероятно, это связано с тем, что HTTP-вызов является асинхронным. Угловой будет оценивать ваш шаблон, и в первый раз, когда это произойдет, свойство quote будет равно нулю. Попробуйте использовать асинхронный канал. https://angular.io/docs/ts/latest/api/common/AsyncPipe-class.html – toskv
также до тех пор, пока HTTP-вызов не будет выполнен, поле quote будет просто пустым. Когда угловая оценка {{quote.contents.quotes.quote}} приведет к этой ошибке. потому что на этом объекте нет свойства содержимого. – toskv
@toskv благодарит за вашу помощь, позвольте мне попробовать вас предложить, и я вернулся. –