簡體   English   中英

如何在服務angular中獲取JSON的數據

[英]How to get data from JSON in a service angular

我有一個 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){
...

不想工作,它給了我錯誤

錯誤類型錯誤:無法讀取未定義的屬性“數據”

我不知道為什么相同的 function 在 component.ts 中工作但在服務中不工作的問題在哪里? 我真的很感激你能提供的任何幫助。

這是因為當您在服務內部調用它時,您試圖在它初始化之前訪問用戶 object。 解決此問題的方法是創建一個代表用戶 object 的 class,它具有數據和其他值的默認值。 然后讓 class 的用戶 object。

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

}

然后在AuthUserService類型的UserModel中創建用戶

user: UserModel = new UserModel();

您是否在npm install -g json-server中創建了觀看 json 的命令

json-server --watch src/data/name.json --port 3000

你可能忘了寫 object 的 model

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM