【问题标题】:Angular 6: Fetch Hash Table Data from JSON respond BackendAngular 6:从 JSON 响应后端获取哈希表数据
【发布时间】:2019-03-18 23:46:53
【问题描述】:

我的后端有这个 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
}

我想知道如何实现这一点,使用服务订阅数据和访问数据(以便以后更改并添加数据)。 非常感谢!

【问题讨论】:

  • completedLessons: any[] 听起来很合适。
  • 以及如何订阅和访问数据?
  • 你可以使用这种类型的数组:interface CompletedLesson{[name:string]:number[]}
  • 好的,听起来不错。那我怎么订阅呢?我需要像往常一样做一些特别的事情或订阅吗?
  • 而且 CompletedLesson 是数组吗?我可以通过添加 [] 使其成为数组吗?

标签: json angular typescript interface hashmap


【解决方案1】:

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

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

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

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 中,访问 Mr. 的第一课。 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] });

希望这会有所帮助。

【讨论】:

  • 谢谢!你是什​​么意思做某事的结果?像 this.users = users?
  • 我如何访问 e.x 数组中的第一课?例如,如果我有 [{"3": [1,2,3]}] 那么我如何打印第 1 课?
  • 我编辑了答案,请检查此编辑是否回答了您的评论问题...
  • 是的,这很好!有没有办法以某种方式访问​​“3”?检查课程 ID 是否正确?
  • 以及如何添加到现有数组课程以及如何添加新哈希?
猜你喜欢
  • 1970-01-01
  • 2019-08-08
  • 2017-04-03
  • 1970-01-01
  • 1970-01-01
  • 2019-06-29
  • 2021-10-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多