2

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); } );

returns IP Object in Console

but afterwards, I can't access or convert it :

this.visitorService.getIpAddress().subscribe(ip => { this.ipAdress = ip.ip } );
fdermishin
  • 3,519
  • 3
  • 24
  • 45

2 Answers2

3

If you want to output IP address to console, you can only do it once the value "arrives":

this.visitorService.getIpAddress().subscribe(ip => {
    console.log(ip);
    this.ipAdress = ip;
});
Nenad
  • 24,809
  • 11
  • 75
  • 93
1

Just use desired property and it is good practice to handle errors. You can see what properties are available by using console.log() - it will show your properties:

console.log(this.visitorService.getIpAddress()
    .subscribe(ip => {
        console.log(`your ip`, ip);
        this.ipAdress = ip['yourProperty'];
        },
    err => {
        console.log(err);
    });

UPDATE:

Your code looks ok for me. However, it can be improved by using pipe method just one time. pipe method is used to chain methods:

login(username: string, password: string): Observable<User> {
    // der globale interceptor (jwt) hängt halt auch 
    // hier das authorization header feld hinzu; macht nichts

    return this.http.post<UserRaw>(
      `${environment.apiUrl}/login`, { username, password } )
      .pipe(map(userRaw => UserFactory.fromRaw(userRaw)),
            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;
      }));

You can read more in Angular 2 Style Guide

StepUp
  • 36,391
  • 15
  • 88
  • 148
  • I would just add that string as a third parameter to my login-service. That's why I want to "unwrap" the Observable within my login method. do you think that's good practice? Please notice the edited question. –  Apr 21 '20 at 10:12
  • so I should "fully suscribe" to this (with an pipe/map and an error handler) as i would with an observable received from a remote API? –  Apr 21 '20 at 10:30
  • @Roger no, you need to `subscribe` only in your component. – StepUp Apr 21 '20 at 10:41
  • I'm using the VisitorsService.getIPAddres inside another service (AuthService.Login) ...i just want to get that string and then proceed with it.. –  Apr 21 '20 at 10:45
  • @Roger You need to create a parameter `ipAddress` for `AuthService.Login()` and send `ipAddress` as parameter to ``AuthService.Login()`` – StepUp Apr 21 '20 at 10:50
  • yeah, but first I shoild probably "extract" the IP from that Object into a primitive string. Later I might de-couple it and create a Service such as "trackVisitor" or something) –  Apr 21 '20 at 10:57
  • @Roger yeah, create another service for getting ip and then send it to place where it is necessary – StepUp Apr 21 '20 at 11:58