【问题标题】:Angular HTTP Error while trying to obtain IP address from api.ipify.org尝试从 api.ipify.org 获取 IP 地址时出现 Angular HTTP 错误
【发布时间】:2019-09-10 19:09:36
【问题描述】:

我是 Angular 的新手。我正在尝试使用 api.ipify.org API 获取客户端的 IP 地址。下面显示的代码出现错误。谁能建议我如何解决这个问题。

来自 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/');
  }

}

下面的代码来自登录组件

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

下面的代码来自 login.html

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

下面是我得到浏览器控制台的错误

即使在将 CommonService 添加到提供程序数组之后...它显示另一个错误

【问题讨论】:

  • 在 Providers 数组中添加CommonService
  • 尝试复制,看看是否有效
  • 在将提供程序添加到 module.ts 后仍然出现错误
  • @PrashantPimpale 你告诉我的代码不适用于我的代码.....

标签: angular typescript


【解决方案1】:

您在错误的班级提供了Injectable()。您已将您的课程 IP 设为可注射而不是您的服务。将该代码的位置更改为:

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

// ....

【讨论】:

  • 我只生成了这样的服务......它已经存在于代码中......
  • 如果您不向我们展示,我们怎么知道?请提供minimal reproducible example 以便能够正确帮助您。
  • @AGT_82 抱歉……请看一下……我没有添加,因为它是由 ng 命令自动生成的……
  • 现在检查答案,您在错误的课程中提供了注射剂;)
  • 那么我应该在哪里更改类 ip
猜你喜欢
  • 1970-01-01
  • 2011-01-12
  • 1970-01-01
  • 2018-05-08
  • 1970-01-01
  • 1970-01-01
  • 2018-06-23
  • 2014-02-23
  • 2016-11-08
相关资源
最近更新 更多