【问题标题】:Converting HTTP response json into typescript Object in Angular8在Angular8中将HTTP响应json转换为打字稿对象
【发布时间】:2019-11-04 19:51:47
【问题描述】:

我正在尝试从 angular8 中的 HTTP 响应创建一个打字稿对象,但我收到一个错误:

错误参考错误:未定义配置文件 在 SafeSubscriber._next (app.service.ts:17) 在 SafeSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.__tryOrUnsub (Subscriber.js:196) 在 SafeSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.next (订阅者.js:134) 在 Subscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._next (订阅者.js:77) 在 Subscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (订阅者.js:54) 在 MapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/map.js.MapSubscriber._next (map.js:41)

我的 Profile.ts 文件是:here 我的 app.service.ts 文件是:here

我用这个服务结果构造了一个组件类对象,我也得到了错误

错误类型错误:无法读取未定义的属性“名称”

当我在 HTML 文件中使用它时。

服务文件中语句的控制台输出为:

{
  name: "somename",
  status: "sometext",
  bio: "sometext",
  email: "email",
  gitlab: "link",
  twitter: "link",
  instagram: "link",
  linkedin: "link",
  telegram: "link"

},

这是伴随错误的输出。

我的 HTML 代码很快就是:

<p class="ui header">{{profile.name}}</p>

我的组件类文件是:here

【问题讨论】:

  • 对上述问题添加更新,现在,服务中的 console.log(this.profile) 语句打印数据。但是在组件中,没有打印数据。不知道为什么?

标签: javascript angular typescript angular8


【解决方案1】:

问题在于您的AppServicegetProfile() 方法。您正在从此方法返回 this.profile,相反,您应该返回一个像这样的 observable:

getProfile(): Observable<Profile> {
    return this.http.get(this.profileApiUrl) 
               .pipe(
                  map(pro => new Profile(pro))
               );
  }

现在在组件中像这样在组件构造函数中注入这个服务:

//have a class variable
//this will be used in the template to render the profile
profile: Profile;
constructor(private _appService: AppService) {}

ngOnInit() {
 this._appService.getProfile().subscribe(pro => {this.profile = pro;});
}

在模板中使用安全运算符 -

<p class="ui header">{{profile?.name}}</p>

【讨论】:

  • 它不起作用,我尝试了你的更改,产生了一个额外的错误,“Profile is not a constructor”。
  • @Sivaramakrishnan 您的 Profile 类中有一个构造函数。
  • @Sivaramakrishnan 分享您的更新代码;我分享的代码对我有用。这是其他问题。
  • 数据还没有打印出来。
【解决方案2】:

您不需要额外的代码来映​​射到Profile 对象。 HttpClient 会为你做这件事。 您需要对 service.ts 进行一些更改,如下所示:

getProfile(): Observable<Profile> {
    this.http.get<Profile>(this.profileApiUrl)
    .pipe(map((pro: any) =>{
      this.profile = pro;
      return pro
    });
  }
}

在组件中:

ngOnInit() {
 this._appService.getProfile().subscribe(pro => this.profile = pro;);
}

在你的 html 中:

<p class="ui header">{{profile?.name}}</p>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-10
    • 1970-01-01
    • 1970-01-01
    • 2019-07-04
    • 2018-09-18
    • 2020-12-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多