Angular 订阅,如何让方法有订阅
Angular subscribe, how do I make a method have a subscription
我是 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)....
所以我可以检查成员是否已成功创建。
我会做这样的事情
组件
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));
}
我是 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)....
所以我可以检查成员是否已成功创建。
我会做这样的事情
组件
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));
}