【发布时间】: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