How to get IP address on page load in Angular 4

Discussão em 'Angular' iniciado por Code Hunter, Dezembro 3, 2024.

  1. Code Hunter

    Code Hunter Guest

    I'm working in an Angular4 project. I'm trying to get system IP address on page load and pass it to the API for storing the IP address in a MSSQL database. But two rows get inserted on each page load and the IP address in showing as "undefined".

    This is my app.component.ts code

    import {Component, OnInit} from '@angular/core';
    import { HttpClient } from '@angular/common/http';


    @Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
    })
    export class AppComponent implements OnInit{
    publicIP;
    res;
    constructor(private http: HttpClient) {}
    ngOnInit() : void
    {
    this.getip();
    this.http.get("http://localhost:57036/api/data/GetClientIp/?
    IP_Address="+this.publicIP).subscribe(data=>{
    this.res=data as string[]});
    }

    getip()
    {
    this.http.get('http://freegeoip.net/json/?callback').subscribe(data => {
    this.publicIP=data['ip'];});
    }
    }


    I got the IP address in data but while assigning the value to PublicIP it is showing as "Undefined"

    this.http.get('http://freegeoip.net/json/?callback').subscribe(data => {
    this.publicIP=data['ip'];});

    Continue reading...

Compartilhe esta Página