左侧有菜单栏,右侧有内容部分。 每当我点击左侧的菜单,http.get请求被执行,我收到了响应数据,但我不知道如何替换内容div。 谢谢,如果有人帮助我......
组件ts
import {Component} from 'angular2/core';
import {Http} from "angular2/http";
import {HTTPTestService} from "./http-test.service";
import {HTTPSecondComponent} from "./http_second.component";
import {Observable} from 'rxjs/Rx';
@Component({
selector: 'http-test',
template: ` <div class="leftside">
<ul> //left side menu iteration
<li *ngFor="#item of getData?.items" (click)="getPosts()">
<a href="#">{{item.name}}
</a>
</li>
</ul>
//content to display ======= where i struggle to update data
<div *ngFor="#data of postData?.datas"> {{data.creation_date}}
</div>
</div>
`,
directives: [HTTPSecondComponent],
providers:[HTTPTestService],
styleUrls:["../src/css/http-style.css"]
})
export class HTTPTestComponent {
public getData;
public postData;
public displayName;
public creationDate;
constructor (private _httpService: HTTPTestService){}
getStack()
{
this._httpService.getItemData()
.subscribe(
data =>this.getData = (data),
// console.log(this.httpData);},
error => alert(error),
() =>console.log("finished")
);
}
getPosts(){
this._httpService.getPostData()
.subscribe(
data =>this.postData = (data),
// console.log(this.httpData);},
error => alert(error),
() =>console.log("finished")
);
}
ngOnInit() {
this.getStack();
this.getPosts();
}
}
服务ts
import {Injectable} from "angular2/core";
import {Http} from "angular2/http";
import 'rxjs/add/operator/map';
@Injectable()
export class HTTPTestService {
constructor(private _http: Http) { }
getItemData(){
return this._http.get('https://api.stackexchange.com/2.2/sites').map(res => res.json());
}
getPostData(){
return this._http.get('https://api.stackexchange.com/2.2/posts?order=desc&sort=activity&site=stackoverflow').map(res=>res.json());
}
}
点击菜单链接时接收内容数据
{
"datas": [
{
"owner": {
"reputation": 3589,
"user_id": 1376277,
"user_type": "registered",
"accept_rate": 34,
"profile_image": "https://www.gravatar.com/avatar/195fcc7db00488b207c67ccfee6a2c5b?s=128&d=identicon&r=PG",
"display_name": "Rahul Gupta",
"link": "http://stackoverflow.com/users/1376277/rahul-gupta"
},
"score": 1,
"last_edit_date": 1483342788,
"last_activity_date": 1483342788,
"creation_date": 1423733190,
"post_type": "question",
"post_id": 28473725,
"link": "http://stackoverflow.com/q/28473725"
}
]
}
答案 0 :(得分:0)
你班上有ngOnInit。 但除非OnInit没有实现,否则不会执行。
要正确使用它(确保它将被启动),您必须将您的类扩展为实现OnInit。像这样更改类标题的第一行:
export class HTTPTestComponent implements OnInit {
并将OnInit添加到导入行,如下所示:
import {Component, OnInit} from 'angular2/core';
你的函数getStack()和getPosts()将在start
执行