如何从服务角度的JSON中获取数据

时间:2020-02-22 16:17:15

标签: javascript angular typescript

我有一个看起来像这样的JSON文件

{
 "user": [
    {
      "id": 0,
      "data": [
        {
          "userName": "iheb",
          "useremail": "",
          "userPassword": "kkk"
        }
      ],
      "questionnaireListe": [
        {
          "questionnaire": [
            {
              "id": 2,
              "section": [
                {
                  "sectionName": "produit 1",
                  "question": [
                    {
                      "questionName": "question 1",
                      "answer": [
                        {
                          "answerName": "reponse 1"
                        }
                      ]
                    }
                  ]
                },
                {
                  "sectionName": "produit 2",
                  "question": [
                    {
                      "questionName": "question 2",
                      "answer": [
                        {
                          "answerName": "reponse 1"
                        },
                        {
                          "answerName": "reponse 2"
                        }
                      ]
                    }
                  ]
                }
              ]
            }
          ]
        }
      ]
    }
}

和一个具有从其中获取数据的功能的服务

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';


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

  constructor(private _Http:HttpClient) { } 
  getUser() {
    return this._Http.get("http://localhost:3000/user");
  }
}

和一个看起来像这样的component.ts

import { Component, OnInit } from '@angular/core';
import { QuestionnaireService } from '../questionnaire.service';
import { ActivatedRoute, Router } from '@angular/router';
import { Answer } from '../answer';
import { UserQuestion } from '../userQuestion';
import { UserSection } from '../userSection';
import { UserQuestionnaire } from '../userQuestionnaire';

@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {
  user:object;

  ques:Object;
  identifiant:number;
  constructor(public router:Router ,private questionnaire:QuestionnaireService,private activatedRoute:ActivatedRoute) { }

  ngOnInit() {
    this.identifiant = this.activatedRoute.snapshot.params['id'];
    this.afficherUser();
  }
checkChange(event:Event,a:number,b:string,c:string){
  let s=<HTMLInputElement> event.target;
  let aa=true;
  let bb=true;
  let cc=true;
  let f= new Answer(<string>s.value);
  let d= new UserQuestion(c,[f]);
  let e= new UserSection(b,[d]);
  let g= new UserQuestionnaire(a,[e]);
  if (s.checked == true){
    for (let x of this.user['questionnaireListe']){
      for(let y of x.questionnaire){
        if (y.id == a){
          cc=false;
          for(let z of y.section){
            if(z.sectionName == b){
              bb=false;
              for (let u of z.question){
                if(u.questionName == c){
                  aa=false;
                  u.answer.push(f);
                  break;
                }
              }
              if(aa == true) {
                z.question.push(d);           
                aa=false;       
                break;
              }
            }
          }
          if(bb == true){
            y.section.push(e);
            bb=false;
            break;
          }
        }
      }
      if(cc == true) {
        x.questionnaire.push(g); 
        cc =false;
        break;
      }
      }
    }
    else{
      for (let x of this.user['questionnaireListe']){
        for(let y of x.questionnaire){
          if (y.id == a ){
            for(let z of y.section){
              if(z.sectionName == b ){
                for (let u of z.question){
                  if(u.questionName == c && u['answer'].length >= 2){
                    let y= u.answer.indexOf(f);
                    u.answer.splice(y,1);
                  }
                  else if(u.questionName == c && u['answer'].length == 1){
                    let xx= z.question.indexOf(d);
                    z.question.splice(xx,1);

                  }
                }
              }
            }
          }
      }
    }
  }
}
}

我有一个看起来像这样的服务

import { Injectable, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { QuestionnaireService } from './questionnaire.service';
@Injectable({
  providedIn: 'root'
})
export class AuthUserService implements OnInit{
user:Object;
aa=true;
  constructor(private router:Router, private questionnaire:QuestionnaireService) { }
  logIn = false;

  ngOnInit(){
    this.afficherUser();

  }
  afficherUser(){
    this.questionnaire.getUser().subscribe(Response=>{ 
     this.user=Response;
    })
  }


  login(t){


  for (let x of this.user['data']){
    if (t.userName == x.userName && t.userPassword == x.userPassword){
        this.aa=false;
        this.router.navigateByUrl('/userQuestionnaireListe');
      } 
    }
      if (this.aa == true){
        this.router.navigateByUrl('/login-user');      
      }
  }
}

所以我在组件中使用的方法

for (let x of this.user['questionnaireListe']){
      for(let y of x.questionnaire){
        if (y.id == a)
...

工作正常,但是当我在服务中使用它


  for (let x of this.user['data']){
    if (t.userName == x.userName && t.userPassword == x.userPassword){
...

不想工作,它给了我错误

错误TypeError:无法读取未定义的属性“数据”

我不知道为什么相同的功能可以在component.ts中起作用而在服务中却不起作用呢? 我非常感谢您可以提供的任何帮助。

2 个答案:

答案 0 :(得分:-1)

这是因为在服务内部调用它时,您试图在初始化用户对象之前访问它。解决此问题的方法是创建一个代表用户对象的类,该类具有数据的默认值和其他值。然后使该类的用户对象。

class UserModel {
 id: number;
 data = [];
 questionnaireListe = [];

}

然后在 UserModel

AuthUserService 类型内创建 user
user: UserModel = new UserModel();

答案 1 :(得分:-1)

您是否在命令行中执行了观看json的命令 npm install -g json-server

json服务器--watch src / data / name.json --port 3000

您可能已经忘记编写对象的模型了