Angular 6:从JSON响应后端获取哈希表数据

时间:2018-10-14 10:15:46

标签: json angular typescript interface hashmap

我的后端有此JSON响应:

//User_Courses

[
  {
    id: 1,
    name: "Ice King",
    email: "pretty_princess1234@gmail.com"
    completedCourses: [1,3],
    unlockedCourses:  [1,3,4,5,6],
    completedLessons: [{"1" => [1,2,3]}, {"3" => [1,2,3,4,5,6,7]}, {"4" => [1]}]
  },
  {
    id: 2,
    name: "Mr. Crocker",
    email: "fairy_godparents111@gmail.com"
    completedCourses: [3],
    unlockedCourses:  [1,3,4],
    completedLessons: [{"3" => [1,2,3,4,5,6,7]}, {"4" => [1,2]}]
  }
]

// completed lessons are all the lesson the user finished. 
// courses can be in progress or completed.

我想从后端获取数据并将其订阅到此接口。 我不确定如何实现数据结构以及如何访问数据。 这是我创建的界面:

export interface IUser {
  id: number;
  name: string;
  email: string;
  completedCourses: number[];
  unlockedCourses: number[];
  completedLessons: // <----- don't know what type to write
}

我想知道如何实现此功能,使用服务订阅数据并访问数据(以便以后进行更改并添加数据)。 非常感谢!

1 个答案:

答案 0 :(得分:2)

CompletedLesson 创建模型(如注释中所述):

interface ICompletedLesson {
    [name: string]: number[];
}

interface IUser {
    id: number;
    name: string;
    email: string;
    completedCourses: number[];
    unlockedCourses: number[];
    completedLessons: ICompletedLesson[];
}

然后,创建一个服务,如下所示:

@Injectable()
export class UserService {

    constructor(private http: HttpService) { }

    fetchUserCourses(): Observable<IUser[]> {
        return this.http.get<IUser[]>(`URL_TO_THE_USER_COURSES%);
    }
}

而且,无论您在哪里获取数据(例如某些 component ):

fetchUserCourses() {
    // userService is injected in this component's constructor
    this.userService.fetchUserCourses().subscribe(users => {
        // do something with result, yes, something like
        this.users = users;
    });
}

在您提供的JSON中,访问先生的第一课。 Crocker 完成的课程(this.users是您从后端检索到的所有用户):

const firstCompletedLesson = this.users[1].completedLessons[0];   // {"3": [1,2,3,4,5,6,7]}
const lessons = firstCompletedLesson["3"];  // [1,2,3,4,5,6,7]
const firstLesson = lessons[0];  // 1

此外,您可以这样访问“ 3”:

Object.keys(firstCompletedLesson)[0];   // 3

,您可以使用 push 添加到数组:

lessons.push(8);   // [1,2,3,4,5,6,7,8]

并添加新的完整课程用途:

this.users[1].completedLessons.push({ "5": [1, 2, 3] });

希望这会有所帮助。