我知道那边有很多有关如何使用RXJ/可观察到的教程。
我需要一些非常简单的示例,以查看如何使用http
使用map
,subscribe
和catch
方法使用可观察到的angular2服务。
到目前为止,我能够生成一项服务,以获取带有休息端点的通信:
@Injectable()
export class UsersApi {
protected basePath = 'http://localhost:8082/commty/cmng';
constructor(protected http: Http) {
}
public create(user: string, passwd: string, extraHttpRequestParams?: any): Observable<{}> {
return this.createWithHttpInfo(user, passwd, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
public createWithHttpInfo(user: string, passwd: string, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + `/users`;
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'user' is not null or undefined
if (user === null || user === undefined) {
throw new Error('Required parameter user was null or undefined when calling create.');
}
// verify required parameter 'passwd' is not null or undefined
if (passwd === null || passwd === undefined) {
throw new Error('Required parameter passwd was null or undefined when calling create.');
}
// to determine the Content-Type header
let consumes: string[] = [
];
// to determine the Accept header
let produces: string[] = [
'application/json'
];
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Put,
headers: headers,
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = this.extendObj(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
我已经使用了map
方法,但我不太了解它的代表。
我需要如何使用UserApi.create(user, password)
方法?
编辑
由于没有A subscription ,http.get(...)
方法将无法执行,所以我发现我需要任何东西:
userApi.create('user', 'password').subscribe(...)
有人可以填写subscribe
方法吗?
映射功能采用可观察到的数据,使用提供给它的功能并返回可观察到的新功能。您仍然需要订阅此新观察的新过程。
在您的示例中,可观察到的只能返回一个响应。地图功能将采用此响应,并将其转换为未定义的状态,如果其状态为204或否则包含的JSON。
要从此类外部使用它:
class TestClass {
constructor(private usersApi: UsersApi ) {}
public testFunction() {
this.userApi.create("user", "pass").subscribe(
(result: any) => { // <-- handler for result
console.log(result);
},
(error: any) => { // <-- handler for error
console.log(error);
},
() => { // <-- handler for done
console.log("Done");
},
);
}
}
map()
只是转换流事件值。
您可以从传递的流中获得事件值,可以进行一些转换,例如response.json()
,结果是用于关注运算符或subscribe()
没有subscribe()什么都不会发生。如果您不订阅,则http.get()不会导致对服务器的请求。
如果使用|异步管,那么您就无需订阅自己。管道为您
您需要subscribe
可观察的功能才能实际执行服务。
UserApi.create(user, password).subscribe(
res=> {//do stuffs that have remote data "res" here},
error=> {//do what when "error" happens},
() => console.log('Completed!')
)