【问题标题】:How to get only one user instead of a list?如何只获得一个用户而不是列表?
【发布时间】:2020-03-04 15:14:24
【问题描述】:

我尝试从用户列表中仅获取一个用户并在另一个页面上显示他的个人资料。

我想使用 routerLink 执行此操作,并将此特定用户的 id 传递到下一页。

路由正在运行,我被定向到个人资料页面,但是当我记录 http 请求的结果时,我仍然会返回用户页面中的整个用户列表,而不是一个用户的详细信息。

我已经尝试了很多事情,比如在我的 user.service.ts 中更改 url 的路径,但这并没有解决问题我什至在使用此路径 ${this.url}/users/${id}/ 而不是 ${this.url}/users/?i=${id}/ 时遇到 404 请求错误(其中它的工作)。

尽管 id 是一个整数,但 api 文档说,为了检索一个单个用户,它的 http://1234//users/{id}/ 它是这个方案。但是当我想应用该方案时,我得到了 404 错误。

这就是我必须使用?I= 版本的原因,但问题是我只能在下一页获得完整的用户列表。

我的代码:

user.service.ts

// get a user's profile
  getUserDetails(id): Observable<any> {
    return this.http.get(`${this.url}/users/?i=${id}/`); // why add ?i
  }

user.page.ts

// get all users in the users page
  getAllUsers() {
    this.userList = this.userService.getList()
    .pipe(map(response => response.results));
  }

user.page.html

   <ion-avatar  class="user-image"  slot="start" [routerLink]="['/','profile', 'user.id']">
            <ion-img src="assets/22.jpeg"> </ion-img>
     </ion-avatar>

profile.page.ts

 information = null;
...
  ngOnInit() {
     // Get the ID that was passed with the URL
     let id = this.activatedRoute.snapshot.paramMap.get('id');

     // Get the information from the API
     this.userService.getUserDetails(id).subscribe(result => {
       this.information = result;
       console.log(result);
     });
   }

【问题讨论】:

  • 我假设 ${this.url}/users/?i=${id} 会给你用户列表,因为参数甚至可能无关紧要,所以它基本上与 $ 相同{this.url}/用户/。您说文档提到要获得一个人,url 应该是 ${this.url}/users/${id}。我建议找出使用该网址时出现错误的原因
  • 远射,只是为了确定:它说的是/users/{id}而不是/user/
  • 不是它的说法/users/{id}
  • @rtpHarry 我想我知道问题所在。因为 id 必须是一个数字。我将如何更改 let id = this.activatedRoute.snapshot.paramMap.get('id'); 以便获取数字?
  • 一旦变成查询字符串,它就不是数字了,所以在这种情况下它没有任何区别。如果你真的想的话,你可以使用parseInt()

标签: javascript angular typescript ionic-framework ionic4


【解决方案1】:

好像网址有误。如果是我,我会 console.log 网址并将其与文档进行比较。这里有一个 sn-p 来尝试一些变化:

    const id = 1;

    const options = [
      `${this.url}/users/?i=${id}/`,
      `${this.url}/users/?i=${id}`,
      `${this.url}/users/i/${id}/`,
      `${this.url}/users/i/${id}`,
      `${this.url}/user/?i=${id}/`,
      `${this.url}/user/?i=${id}`,
      `${this.url}/user/i/${id}/`,
      `${this.url}/user/i/${id}`,
    ];

    for (const option of options) {
      try {
        const response = await this.http.get(option);
        console.log(options, response);
      } catch (e) {

      }
    }

我也会考虑放弃第二个 http 请求。如果第一个请求返回所有需要的数据,您可以将其存储在服务的变量中。

【讨论】:

    猜你喜欢
    • 2021-05-26
    • 1970-01-01
    • 2021-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多