我是Angular 2的新手,不知道如何订阅。 我有一个类似(简单版本)的会员服务:
import { Injectable, NgZone, Output, EventEmitter } from '@angular/core';
import { Network } from '@ionic-native/network';
import { HttpProvider } from '../providers/http-provider';
@Injectable()
export class Member {
firstName:string = "";
surname:string = "";
constructor(private httpProvider: HttpProvider, private network: Network, zone: NgZone) {
}
createMember(member){
this.httpProvider.createMember(member).subscribe(
result => {
var data = JSON.parse( result['_body'] );
this.firstName = member.FirstName;
this.surname = member.Surname;
return true;
},
err =>{
console.error("Error : "+err);
return false;
}
);
}
}
然后我有另一个使用成员服务的组件,我希望有类似的东西:
this.member.createMember(member).subscribe(data)....
所以我可以检查成员是否已成功创建。
答案 0 :(得分:1)
我会做这样的事情
组件
this.membersService.createMember(member)
.subscribe(res => {
console.log('success', res)
}, err => {
console.log('error', err);
});
服务
import {Injectable} from '@angular/core';
import {Http, RequestOptions, Response, Headers} from '@angular/http';
import 'rxjs/Rx';
createMember(member) {
const body = JSON.stringify(member);
const headers = new Headers({
'Content-Type': 'application/json'
});
const options = new RequestOptions({headers: headers});
return this.http.post('/api/members', body, options)
.map((res: Response) => res.json())
.catch((err: any) => console.log(err));
}