【问题标题】:How do I access json key in Angular 4.3 with the new HttpClient?如何使用新的 HttpClient 在 Angular 4.3 中访问 json 键?
【发布时间】:2018-08-19 13:41:35
【问题描述】:

我正在尝试从 Angular 4.0 迁移到 4.3,以便逐步升级到 Angular 5 或 6。

我开发了一个简单的身份验证,对每个请求都使用jwtjwt 存储在本地存储中。

我只知道 4.3 版本现在使用 HttpClientModule 将被声明为

app.module.ts

import { HttpClientModule } from '@angular/common/http';
imports: [
HttpClientModule,
]

我正在使用一项服务进行身份验证、注册用户和加载令牌。

auth.service.ts

import { Injectable } from '@angular/core';
//import { Headers } from '@angular/http';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import 'rxjs/add/operator/map';

@Injectable()
export class AuthService {

  authToken: any; // class property so we can access it anywhere
  user: any;

  constructor(private http:HttpClient) { }

  authenticateUser(user) {
    let headers = new HttpHeaders();
    headers.append('Content-Type', 'application/json');
    return this.http.post('http://localhost:3000/users/authenticate', user, {headers: headers})
  }

  storeUserData(token, user) {
    // code for storing user data
  }

  logout() {
    this.authToken = null;
    this.user = null;
    localStorage.clear();
  }
}

login.component.ts

import { AuthService } from 'app/services/auth.service';

@Component({
})
export class LoginComponent implements OnInit {

  username: String;
  password: String;

  constructor(
    private _flashMessagesService: FlashMessagesService,
    private authService: AuthService,
    private router: Router
  ) { }

  ngOnInit() {
  }

  onLoginSubmit() {

    const user = { 
      username: this.username,
      password: this.password
    }

    this.authService.authenticateUser(user).subscribe(data => {
      // console.log(data);

      if(data.success) {
        this.authService.storeUserData(data.token, data.user);
        this.router.navigate(['admin']); //redirect
      } else {
        this.router.navigate(['login']); //redirect
      }
    });
  }
}

我在 login.component.ts 文件中收到上述错误提示。

login.component.ts (43,15):类型上不存在属性“成功” '对象'。

我尝试在控制台中打印data,这就是我看到的:

{success: true, token: "JWT dlskdlskdlskdlsdklgfdg;kfd;gkd;432ks;dfks;fks;fkds;f", user: {…}}
success: true
token:"JWT dlskdlskdlskdlsdklgfdg;kfd;gkd;432ks;dfks;fks;fkds;f"
user:{id: "95430590435934fkdlkfldskfds", name: "Carlo K", username: "carlok", email: "carlok@gmail.com"}

你知道如何从上面的 console.log 访问data 吗?

我想在 login.component.ts 中像这样使用data

if(data.success) {
// do code
}

任何想法都值得赞赏。谢谢

Note:如果我在 app.module.ts 和 Http 对象中使用 Angular 4.0 -- HttpModule,我不会遇到上述错误

【问题讨论】:

  • .subscribe(data => { 更改为.subscribe(data:any => { 或者,您可以将authenticateUser(user) 更改为authenticateUser(user): Observable<any>
  • 尝试:订阅(data => { if(data){ if(data.success){}}}
  • @user184994 感谢f或快速响应,但没有运气..
  • @PrashantPimpale 错误还是一样..
  • 出现同样的错误?您介意用您尝试过的内容更新问题吗,因为这应该可以通过删除对该值的类型检查来防止该错误

标签: javascript php ajax angular mongodb


【解决方案1】:

新的HttpClientModule 希望您为您的http 调用提供return type / interface。任何没有指定type 的调用都将转换为Object。这意味着,要解决您的问题,您可以采用以下任一方法,首选选项 3(最佳实践)。

  1. 提供any类型,将这一行从return this.http.post(...)改为return this.http.post<any>(...)

  2. 提供any类型,将这一行从 this.authService.authenticateUser(user).subscribe(data => ...this.authService.authenticateUser(user).subscribe(data: any => ...

  3. 强类型它。例如。创建一个接口并使用它。 interface Data { success: boolean; token: string; user: any; }。将此行从 return this.http.post(...) 更改为 return this.http.post<any>(...)

【讨论】:

  • 感谢您的快速回复。如果我继续使用选项 3,我应该在 login.component 文件或 auth.service.ts 文件中的哪里创建接口?
  • 这取决于你的项目结构。通常,在我的项目中,我设置了一个文件夹来保存所有接口和类 ts 文件。将文件夹命名为 models(如在数据模型中)或 interfaces。由你决定。 :)
  • 我明白了。谢谢@Chybie,你很棒。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-04-03
  • 1970-01-01
  • 2018-05-25
  • 2018-11-07
  • 2018-04-24
  • 1970-01-01
  • 2018-02-09
相关资源
最近更新 更多