这可能是一个基本问题。但我是 Angular 服务( promise 、可观察等)的新手。
基本上,我在登录页面中有一个按钮(登录),一旦用户单击该按钮,我想验证并生成 token 。一旦在服务上分配了 token 字段,我就会重定向到某个页面(主页)。但是现在发生的事情是,当我对 Angular 服务函数进行函数调用时,在它获取(异步) token 本身之前,我的页面正在重定向。
应用数据服务
`
import { Injectable } from '@angular/core';
import { HttpClient,HttpHeaders } from '@angular/common/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/mergeMap';
import 'rxjs/add/operator/toPromise';
@Injectable()
export class AppDataServiceService {
tokenGenerated:any='';
constructor(private http: HttpClient) {
}
getData(){
console.log("Started.. in service");
this.http.get('http://host/url').toPromise()
.then(this.extractData);
}
private extractData(res: Response) {
console.log("completed.. in service");
this.tokenGenerated=res;
return res;
}
}
`---------------------------------------------------
login component
import { Component, OnInit } from '@angular/core';
import { AppDataServiceService } from '../app-data-service.service';
import { Router } from '@angular/router';
@Component({
selector: 'app-login-component',
templateUrl: './login-component.component.html',
styleUrls: ['./login-component.component.css']
})
export class LoginComponentComponent implements OnInit {
constructor(private dataService:AppDataServiceService,private router:Router) {
}
ngOnInit() {
}
submit(){
this.dataService.getData();
console.log('after executing service');
this.router.navigate(['/view']);
};
}
-------------------------------------------------------------
login html
<div class="container">
<label><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="uname" >
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" >
</div>
<input type="button" (click)='submit()' value="Login" name="submit"/>
浏览器中的控制台输出:
开始..投入使用
执行服务后
已完成..投入使用
你能帮我让http调用等到它完成吗?我不确定这是否是使用 promise 使调用同步的方式。
最佳答案
您应该从您的服务返回一个 promise (或 Observable),并在组件中订阅它。
如果不这样做,组件就无法知道您的异步代码何时完成执行,因此它会立即打印该日志语句
像这样更改服务:
getData(){
console.log("Started.. in service");
return this.http.get('http://host/url').toPromise()
.then(res => this.extractData(res));
}
然后在组件中
submit(){
this.dataService.getData().then(() => {
console.log('after executing service');
this.router.navigate(['/view']);
};
};
关于javascript - 等待 angular 4 服务中的 http 请求完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48119369/