[英]Unable to trigger http.post in angular2 provider
我聽起來可能很蠢,但是我是angular2的新手。 我正在處理ionic2上的項目,我編寫了一個auth-service,它具有功能IsEmailAvailable()來對輸入標簽進行異步驗證。
我無法觸發http.post請求。 我已經嘗試了許多教程。 我知道angular2中的http返回Observable具有很多優點。 我嘗試將http.post轉換為.toPromise,也嘗試使用.then。 仍然沒有進展。
this.http.post(MyApp.BASE_URL+"/api/auth/email",body).map(res => res.json())
.subscribe(
res => {console.warn("some thing")},
err => { console.error("some bullshit")},
() => {console.log('Authentication Complete')}
);
編輯1
public isEmailAvailable(control : Control) {
return new Promise(resolve => {
let body = JSON.stringify({username: control.value});
console.log(body);
let headers = new Headers({ 'Content-Type': 'application/json' });
this.http.post(MyApp.BASE_URL+"/api/auth/email",body).map(res => res.json())
.subscribe(
res => {console.warn("some thing")},
err => { console.error("some bullshit")},
() => {console.log('Authentication Complete')}
);
});
}
編輯2只是為了增加更多的見解。 我在提供程序中使用了isEmailAvailable函數,並在signup.ts頁面中將其用作異步驗證器:
constructor(private navCtrl: NavController, formBuilder : FormBuilder,
public globalVars : GlobalVars, public userData: UserData, public
authService : AuthService)
{
this.nav = navCtrl;
this.signUpForm = formBuilder.group({
email : [
'',Validators.compose([]),authService.isEmailAvailable],
password: ['',Validators.compose([
Validators.maxLength(100),
Validators.minLength(6),
Validators.required,
Validators.pattern(globalVars.getPasswordPattern().toString())])]
});
}
只需刪除Promise.resolve(...)
:
public isEmailAvailable(control : Control) {
let body = JSON.stringify({username: control.value});
console.log(body);
let headers = new Headers({ 'Content-Type': 'application/json' });
return this.http.post(MyApp.BASE_URL+"/api/auth/email",body).map(res => res.json())
.do(res => {console.warn("some thing")})
.catch(err => { console.error("some bullshit"); return Observable.of([err]);})
.toPromise().then(() => {console.log('Authentication Complete')});
確保已導入所有內容( do
, catch
, of
, toPromise
)
無需使用承諾。 而且您不想在函數本身內調用.subscribe()
。 函數應在Observable上訂閱的調用代碼。 我會做:
public isEmailAVailable(control:Control): Observable<any>{
let body = ...;
let headers = ...;
let options = new RequestOptions();
options.headers = headers;
//suppose your server returns TRUE if email is available
return this.http.post('...', body, headers).map(res => res.json())
//async validators should return NULL if field is valid
//or an object with the failure reason
.map(res => res?null: {'Email is unavailable':true});
}
順便說一下,您的原始代碼在POST請求中不包含標頭。 我也解決了。
附錄:如果您必須退還承諾,請改用以下return
:
return new Promise ((resolve) => {
//assumes your server returns TRUE if email is available
this.http.post(...).map(res => res.json()).subscribe(
//validator expects NULL when input is valid
res => res? resolve(null): resolve ({'Email unavailable':true})
);
});
您可以看到它在此插件中工作。 當輸出null
,該輸入被視為有效。 輸出對象時,將其視為無效。
所以,我終於得到它通過手動注入該服務中的HTTP提供商我的服務工作 。 由於某種原因,在構造函數中設置提供程序引用的通常方法在我使用時正常工作
這沒用
http : any;
constructor (httpService : Http)
{
this.http = httpService;
}
這樣,它不能像
更新: 這項工作
isEmailAvailable(control : Control) {
// Manually inject Http
let injector = ReflectiveInjector.resolveAndCreate([HTTP_PROVIDERS]);
let http = injector.get(Http);
return new Promise(resolve => {
let body = JSON.stringify({username:control.value});
let header = new Headers();
header.append("Content-Type" , "application/json");
// HERE I'm using manually injected http
return http.post(MyApp.BASE_URL+"/api/auth/email",body,{ headers: header}).map(res => res.json())
.subscribe(
res => {console.warn("some thing")},
err => { console.error("some bullshit")},
() => {console.log('Authentication Complete')}
);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.