I've found this example of a service to get the IP-Address.
This service returns an Observable<Object>
, which I would like to assign/save to a String-Variable.
getIpAddress() {
return this.http
.get('https://api.ipify.org/?format=json')
.pipe(
catchError(this.handleError)
);
}
I'm still not well "trained" with Observables. I've injected this Service to my own Service (an Authentication Service) where I'm trying to access the actual value, which would be a string.
I know I'll have to subscribe and pipe/map in order to use it, but that's where I'm lost...
console.log(this.visitorService.getIpAddress().subscribe(ip => this.ipAdress = ip ?? ));
Lastly, I want to use the IP-Address (string) inside my login-method (where the console.log will be replaced and the API received this third body param):
login(username: string, password: string): Observable<User> {
// der globale interceptor (jwt) hängt halt auch hier das authorization header feld hinzu; macht nichts
console.log(this.visitorService.getIpAddress().subscribe(ip => this.ipAdress = ip ?? ));
return this.http.post<UserRaw>(
`${environment.apiUrl}/login`, { username, password } )
.pipe(map(userRaw => UserFactory.fromRaw(userRaw)))
.pipe(map(user => {
// local storage = client persistence (user bleibt eingeloggt)
localStorage.setItem('currentUser', JSON.stringify(user));
this.currentUserSubject.next(user);
// console.log(user.username);
return user;
}));
UPDATE
this.visitorService.getIpAddress().subscribe(ip => { console.log(ip); } );
but afterwards, I can't access or convert it :
this.visitorService.getIpAddress().subscribe(ip => { this.ipAdress = ip.ip } );