角2,获取数据不在服务区 [英] Angular 2, Getting Data Out of Service
本文介绍了角2,获取数据不在服务区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
目前,我正在尝试角2和我有看到从我创建的服务返回的数据的麻烦。在开发工具我看到 getSubjects()
API调用射击,但我从来没有看到在视图中显示任何数据。有任何想法吗?我失去了一些东西明显?
SubjectService.ts
进口{}注射从angular2 /芯;
从angular2 / HTTP进口{HTTP,响应,HTTP_PROVIDERS};@Injectable()
出口类SubjectService {
构造函数(公共HTTP:HTTP){ } getSubject(){
返回this.http.request('/ subjects.json')
.MAP(响应= GT; response.json())
。订阅(
RES => this.subjects =资源,
ERR => this.logError(ERR)
);
}
}
DashboardComponent.ts
进口{组件,查看}从'angular2 /核心
从进口{} CORE_DIRECTIVESangular2 /常用
从../../services/subject/SubjectService.ts进口{} SubjectService
进口'rxjs /添加/运营/图;@零件({
选择:仪表盘,
供应商:[SubjectService]
})@视图({
模板:`
< DIV CLASS =行>
< DIV CLASS =中等12列>
< H1>仪表及LT;!/ H1>
{{主题}}
< / DIV>
< / DIV>
`
})出口类DashboardComponent { 构造函数(subjectService:SubjectService){
subjectService.getSubject()
}
}
解决方案
移动
.subscribe(
RES => this.subjects =资源,
ERR => this.logError(ERR)
)
从服务到组件应该工作
构造函数(subjectService:SubjectService){
subjectService.getSubject()。认购(
RES => this.subjects =资源,
ERR => this.logError(ERR)
);
}
I'm currently trying out Angular 2 and am having trouble seeing the data returned from the service I created. In developer tools I see the getSubjects()
api call firing, but I never see any data shown in the view. Any ideas? Am I missing something obvious?
SubjectService.ts
import {Injectable} from "angular2/core";
import {Http, Response, HTTP_PROVIDERS} from "angular2/http";
@Injectable()
export class SubjectService{
constructor(public http: Http){
}
getSubject(){
return this.http.request('/subjects.json')
.map(response => response.json())
.subscribe(
res => this.subjects = res,
err => this.logError(err)
);
}
}
DashboardComponent.ts
import { Component, View } from 'angular2/core'
import { CORE_DIRECTIVES } from "angular2/common"
import {SubjectService} from "../../services/subject/SubjectService.ts"
import 'rxjs/add/operator/map';
@Component({
selector: 'dashboard',
providers: [SubjectService]
})
@View({
template: `
<div class="row">
<div class="medium-12 columns">
<h1>Dashboard!</h1>
{{subjects}}
</div>
</div>
`
})
export class DashboardComponent{
constructor(subjectService: SubjectService){
subjectService.getSubject()
}
}
解决方案
move
.subscribe(
res => this.subjects = res,
err => this.logError(err)
)
from service to component should work
constructor(subjectService: SubjectService){
subjectService.getSubject().subscribe(
res => this.subjects = res,
err => this.logError(err)
);
}
这篇关于角2,获取数据不在服务区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文