这可能是一个基本问题。但我是角色服务的新手(承诺,可观察等)。
基本上,我在登录页面中有一个按钮(登录),一旦用户点击我要验证的那个按钮并生成令牌。一旦在服务上分配了令牌字段,我将重定向到某个页面(主页)。但是现在发生的事情是,当我对角度服务函数进行函数调用之前,它获取(异步)令牌本身,我的页面正在重定向。
应用的数据服务
`
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来使调用同步的方法。
答案 0 :(得分:4)
您应该从服务中返回一个promise(或Observable),并在组件中订阅它。
如果不这样做,组件无法知道异步代码何时完成执行,因此它会立即打印该日志语句
更改服务:
const {
HashRouter,
Switch,
Route,
Link,
NavLink,
} = ReactRouterDOM
const About = () => (
<article>
My name is Moshe and I'm learning React and React Router v4.
</article>
);
const Page = () => (
<Switch>
<Route exact path='/' render={() => <h1>Welcome!</h1>} />
<Route path='/about' component={About}/>
</Switch>
);
const Nav = () => (
<nav>
<ul>
<li><NavLink exact to="/">Home</NavLink></li>
<li><NavLink to="/about">About</NavLink></li>
</ul>
</nav>
);
class App extends React.Component {
render() {
return (
<div>
<Nav />
<Page />
</div>
);
}
}
ReactDOM.render((
<HashRouter>
<App />
</HashRouter>),
document.querySelector("#app"));
然后在组件中
getData(){
console.log("Started.. in service");
return this.http.get('http://host/url').toPromise()
.then(res => this.extractData(res));
}