【发布时间】:2017-07-13 10:17:33
【问题描述】:
Observable Post 的解释
setup.component.ts
import { Component, EventEmitter, OnInit, Output } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { Post } from './model/post';
import { PostService } from './service/post.service';
@Component({
selector: 'setup',
templateUrl: './setup.component.html',
styleUrls: ['./setup.component.scss']
})
export class SetupComponent implements OnInit {
@Output()
change: EventEmitter<string> = new EventEmitter();
postUsers(input){
this.postService.postUser(input)
.subscribe(
post => {
this.post = post
},
err => {
console.log(err);
});
}
clicked(value) {
console.log(value);
this.postUsers(this.input)
// this.change.emit(value);
}
complexForm : FormGroup;
constructor(private postService: PostService) {}
post: Post[];
ngOnInit() {}
}
post.service.ts
import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Post } from '../model/post';
import { Observable } from 'rxjs/Rx';
// Import RxJs required methods
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
@Injectable()
export class PostService {
constructor (private http: Http) {}
private registerUrl = 'http://localhost:2001/api/users/register';
postUser(user:Post) : Observable<Post[]>{
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post(this.registerUrl, user, options)
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body || { };
}
private handleError (error: Response | any) {
// In a real world app, you might use a remote logging infrastructure
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Observable.throw(errMsg);
}
}
model/post.ts
export class Post {
constructor(
public id: number,
public name: string,
public email: string,
public password: string
){}
}
我了解 model/post.ts 的作用,它定义了属性类型,我需要澄清 setup.components.ts 中的 subscribe 方法。 Observable 在clicked() 内部被调用,但我想了解的是,这是如何做到的,因为应用程序可以访问,这样我就可以在操作完成后继续进行this.postUsers(this.input)
通常情况下,我会执行以下操作
this.postUsers(this.input)
.then(function(){
});
如果有人能解释它的工作原理以及如何确认帖子已完成然后运行下一个功能,我真的很高兴
即我有这个
clicked(value) {
console.log(value);
this.postUsers(this.input)
// this.change.emit(value);
}
但我保证我会这样做
clicked(value) {
console.log(value);
this.postUsers(this.input)
.then(function(){
this.change.emit(value);
});
}
我怎样才能让它与 Observables 一起工作?我试图查看通过执行返回的内容
clicked(value) {
console.log(value);
const runThis = this.postUsers(this.input);
console.log(runThis);
// this.change.emit(value);
}
但它返回undefined。
【问题讨论】:
-
my answer还有什么不清楚的地方吗?
标签: javascript angular rxjs observable