【发布时间】:2017-01-16 02:29:43
【问题描述】:
我正在尝试创建一个service.ts 文件,它将处理我在 TypeScript (AngularJs2) 中的所有 Http 请求。
现在我确实得到了正确的响应,但我无法访问 subscribe() 函数之外的属性。让我告诉你我的意思。
APICaller.service.ts:
import { Injectable, Inject } from '@angular/core';
import { Http } from '@angular/http';
import { Evenement } from './models/evenement.model';
import { Deelnemer } from './models/deelnemer.model';
import { Comment } from './models/comment.model';
@Injectable()
export class APICaller {
http : Http
baseUrl:string = "http://10.0.4.161:8080";
constructor(@Inject(Http) httpService) {
this.http = httpService;
}
addNewComment(deelnemerId:number, eventId:number, content:string) : Comment{
let results:Comment = {id: 0, content:"", user: "", status: "", date: ""};
this.http.post(this.baseUrl+"/evenementen/"
+eventId +"/deelnemers/"+deelnemerId+"/addComment"
,{
user: 'developer',
content: content
}).subscribe((response) => {
results = response.json();
console.log("results id: "+ results.id);
});
return results;
}
}
component.ts:(最小化 - 仍然需要清理)
import { APICaller } from '../../apicaller.service';
import { Comment } from '../../models/comment.model';
@Component({
templateUrl: 'build/pages/deelnemer-details/deelnemer-details.html',
providers: [APICaller]
})
export class DeelnemerDetails {
public deelnemer:any;
public http:Http;
public eventObj;
public newComment;
public comments;
public editComment:any;
constructor(private apiCaller : APICaller, private navCtrl: NavController, navParams : NavParams, public toastCtrl : ToastController, public alertCtrl:AlertController, @Inject(Http) httpService) {
this.eventObj = navParams.get("event");
this.http = httpService;
this.newComment = "";
this.deelnemer={};
this.editComment={
id: -1,
edit: false,
content: ""
}
this.getDeelnemer(navParams.get("deelnemer"));
}
addNewComment(){
let test:Comment = {id: 0, content:"", user: "", status: "", date: ""};
console.log("deelnemer id "+this.deelnemer.id);
console.log("eventObj id "+ this.eventObj.id);
console.log("new comment : "+this.newComment);
test = this.apiCaller.addNewComment(this.deelnemer.id, this.eventObj.id, this.newComment);
console.log("new comment id: "+ test.id);
this.comments.push(
test
);
this.newComment="";
}
回复和console.log()
所以似乎在.subscribe() 中它没有设置results 的值。
【问题讨论】:
标签: angular typescript