可观察帖子的解释
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);
}
}
模型/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 .输入)
通常有一个 Promise 我会做以下事情
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
。
最佳答案
与 promises 类似,让您的 postUsers
方法返回一个可观察的(不是订阅)
postUsers(input){
return this.postService.postUser(input);
}
然后你可以像在 promises 中使用 then
一样订阅这个方法。
clicked(value) {
console.log(value);
this.postUsers(this.input).subscribe((response)=> {
this.change.emit(value);
});
}
您还可以将可观察对象转换为 promise 。这样您就不会感到困惑。
import 'rxjs/add/operator/toPromise';
postUsers(input){
return this.postService.postUser(input).toPromise();
}
clicked(value) {
console.log(value);
this.postUsers(this.input)
.then((res)=>{
this.change.emit(value);
});
}
请注意,我没有在回调中使用 function
关键字。如果我这样做,this.change
将引用回调 change
,因为 this
不会引用组件。
关于javascript - Angular 可观察的发布和订阅解释/它是如何工作的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45077755/