简体   繁体   English

如何使用新的HttpClient访问Angular 4.3中的json键?

[英]How do I access json key in Angular 4.3 with the new HttpClient?

I am trying to migrate from Angular 4.0 to 4.3 so I can upgrade step by step to Angular 5 or 6. 我正在尝试从Angular 4.0迁移到4.3,以便可以逐步升级到Angular 5或6。

I developed a simple authentication that uses jwt for every request. 我开发了一个简单的身份验证,将jwt用于每个请求。 The jwt is stored in a local storage. jwt存储在本地存储中。

I just knew that 4.3 version now uses HttpClientModule that will be declared to 我只知道4.3版本现在使用HttpClientModule ,它将被声明为

app.module.ts app.module.ts

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

I am using a service for my authentication, registering user and for loading the token. 我正在使用服务进行身份验证,注册用户和加载令牌。

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

I am prompted with an error above in login.component.ts file. 在login.component.ts文件中出现上述错误提示我。

login.component.ts (43,15): Property 'success' does not exist on type 'Object'. login.component.ts(43,15):类型“对象”上不存在属性“成功”。

I tried to print data in console and this is what I see: 我试图在控制台中打印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"}

Do you know how can I access data from the console.log above? 您知道如何从上面的console.log访问data吗?

I want to use data like this in login.component.ts: 我想在login.component.ts中使用这样的data

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

Any idea is appreciated. 任何想法表示赞赏。 Thanks 谢谢

Note : I don't encounter an error above if i use the Angular 4.0 -- HttpModule in app.module.ts and the Http Object Note :如果我在app.module.ts和Http Object中使用Angular 4.0- HttpModule ,则不会遇到以上错误

The new HttpClientModule would prefer you to provide a return type / interface for your http call. 新的HttpClientModule希望您为http调用提供return type / interface Any call that do not have type specify, will be cast to Object . 没有type指定的任何调用将被强制转换为Object That mean, to solve your issue, you can either of the below approach, option 3 preferred (best practise). 就是说,要解决您的问题,可以采用以下方法之一,首选方法3(最佳实践)。

  1. Provide any type, change this line from return this.http.post(...) to return this.http.post<any>(...) . 提供any类型,将此行从return this.http.post(...)更改为return this.http.post<any>(...)

  2. Provide any type, change this line from this.authService.authenticateUser(user).subscribe(data => ... to this.authService.authenticateUser(user).subscribe(data: any => ... . 提供any类型,将此行从this.authService.authenticateUser(user).subscribe(data => ...更改为this.authService.authenticateUser(user).subscribe(data: any => ...

  3. Strong type it. 强类型。 Eg. 例如。 Create an interface and use it. 创建一个界面并使用它。 interface Data { success: boolean; token: string; user: any; } interface Data { success: boolean; token: string; user: any; } . interface Data { success: boolean; token: string; user: any; } Change this line from return this.http.post(...) to return this.http.post<any>(...) . 将此行从return this.http.post(...)更改为return this.http.post<any>(...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM