有一个首页的组件,有一个每次加载首页都会访问的服务,它给了用户的IP。问题是,如果您重新加载页面或第一次访问它,那么 IP 是未定义的。如果您转到该站点的任何其他组件并返回主页,那么一切正常。所以问题是 - 我不理解和做错了什么?
零件 -
export class StartPageComponent implements OnInit {
constructor(private authService: AuthService) {
}
ngOnInit() {
this.authService.userSpy().subscribe();
}
}
服务 -
@Injectable({
providedIn: 'root'
})
export class AuthService {
ipAddress: string;
constructor(private http: HttpClient) {
this.getUserIP();
}
userSpy() {
const userIPOptions = {
headers: new HttpHeaders({userIP: `${ this.ipAddress }`})
};
return this.http.post(environment.apiAuthUrl + Constants.USER_URL, {}, userIPOptions);
}
getUserIP() {
return this.http.get('https://jsonip.com/').subscribe((res: any) => {
this.ipAddress = res.ip;
});
}
}
问题在于对异步方法的操作的误解。在收到有关用户 IP 的数据之前发送了返回请求。我通过创建一个独立接收 IP 数据并写入 sessionStorage 的服务解决了这个问题:
之后,我在超时的组件中使用此服务。