0

I'm new to Angular. I'm trying to obtain the Client's IP Address using api.ipify.org API. I'm getting error with the below shown code. Can anyone suggest me how to resolve this issue.

Code from CommonService

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';
@Injectable({
  providedIn: 'root'
})
class IP {
  ip: string;
}
export class CommonService {
  constructor(private http: HttpClient) { }
  strIPObservable: Observable<IP[]>;
  getClientIP(){
    return this.strIPObservable = this.http.get<IP[]>('http://api.ipify.org/');
  }

}

Now below code is from the login component

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { HttpErrorResponse, HttpClient } from '@angular/common/http';
import { Form, FormBuilder } from '@angular/forms';
import { CommonService } from '../CommonService/common.service';
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css'],
  providers: [ CommonService ]
})
export class LoginComponent implements OnInit {
  LoginForm: Form;
  private router: Router;
  constructor(private ClsCommon: CommonService) {
  }
  strIP: any;
  ngOnInit() {
    this.strIP = this.ClsCommon.getClientIP();
  }

  OnSubmit(UserID: string, UserPwd: string) {
  }
}

Now below code is from login.html

<span>By Logging in, you accept ClearDesk's T&Cs.</span>
         <br>Your IP Address is => {{ strIP.ip }}
</mat-card-content>

Below is the error that I'm getting Browser console. enter image description here

even after adding the CommonService to the providers array... its showing another error

enter image description here

Naseef Ali
  • 69
  • 11

1 Answers1

0

You have provided the Injectable() at the wrong class. You have made your class IP as the injectable instead of your service. Change the position of that code to:

@Injectable({
  providedIn: 'root',
})
export class CommonService {

// ....
AT82
  • 71,416
  • 24
  • 140
  • 167
  • I have generated the service like that only.... it’s already present in the code.... – Naseef Ali Apr 21 '19 at 12:28
  • Well how can we know if you don't show us that? Please provide a [MCVE] to be able to correctly help you. – AT82 Apr 21 '19 at 12:30
  • @AGT_82 Sorry...please have a look now.... I didnt added that because it was auto generated by the ng command... – Naseef Ali Apr 21 '19 at 12:33
  • Check answer now, you have provided the injectable at wrong class ;) – AT82 Apr 21 '19 at 13:47
  • So where should I change class ip – Naseef Ali Apr 21 '19 at 13:54
  • I'm sorry, don't really understand? You can have the class where you want, I usually have a separate ts file with all models. But the point is, the injectable needs to be marked on your service. – AT82 Apr 21 '19 at 13:56