我是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数组之后,它仍显示另一个错误
答案 0 :(得分:0)
您在错误的课堂上提供了Injectable()
。您已经将您的课程IP
设置为注射剂,而不是服务。将该代码的位置更改为:
@Injectable({
providedIn: 'root',
})
export class CommonService {
// ....