[英]Angular no http request when subscribed via pipe()
I am quite new to angular and tried to check if a username already exists by sending a http request to my server, but my server isn't getting any requests.我对 angular 很陌生,并试图通过向我的服务器发送 http 请求来检查用户名是否已经存在,但我的服务器没有收到任何请求。
in my Service:在我的服务中:
checkUsername(name: string): Observable<boolean> {
return this.http.get(
`${this.api}/checkusername/${name}`
).pipe(
catchError(this.errorHandler)
);
}
in my Validator:在我的验证器中:
export class UsernameExistsVallidatorService implements AsyncValidator{
constructor(private vs: VallidatorsService) { }
validate(control: FormControl): Observable<ValidationErrors | null> {
return this.vs.checkUsername(control.value).pipe(
map(exists => (exists === false) ? null : {
isbnExists: { valid: false }
}),
catchError(() => of(null))
);
}
}
In my server:在我的服务器中:
app.get("/api/checkusername/:name", (req: express.Request, res: express.Response) => {
console.log(req.params.name);
res.json({exists: false});
});
As you can see the server prints every name and for now it answers with {exists: false}.正如你所看到的,服务器打印了每个名字,现在它用 {exists: false} 回答。
If I put如果我把
this.vs.checkUsername(control.value).subscribe(val => console.log(val));
inside my validate function, the server receives everything correctly.在我的验证函数中,服务器正确接收所有内容。
For the getting request from serve you always needs subscribe
对于从服务获取请求,您始终需要
subscribe
http.post (and get, put, delete, etc)
returns a cold Observable
, ie an Observable
for which: http.post (and get, put, delete, etc)
返回一个冷Observable
,即一个Observable
:
its underlying producer is created and activated during subscription
它的底层生产者是在订阅期间创建和激活的
This means the function represented by the Observable is activated only with the subscribe()
method.这意味着 Observable 表示的函数只能通过
subscribe()
方法激活。
or或者
post() : Promise<any> {
return this.http.post(
'/api,
{}
).toPromise();
or或者
post() {
var observable = this.http.post('/api', {})
.map(response => response.json()) // in case you care about returned json
.publishReplay(); // would be .publish().replay()
observable.connect();
return observable;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.