将 HTTP 响应 json 转换为 Angular8 中的打字稿对象

Converting HTTP response json into typescript Object in Angular8

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

ERROR ReferenceError: Profile is not defined at SafeSubscriber._next (app.service.ts:17) at SafeSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.__tryOrUnsub (Subscriber.js:196) at SafeSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.next (Subscriber.js:134) at Subscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._next (Subscriber.js:77) at Subscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (Subscriber.js:54) at MapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/map.js.MapSubscriber._next (map.js:41)

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

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

ERROR TypeError: Cannot read property 'name' of undefined

当我在 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>

我的组件 class 文件是:here

问题出在您 AppServicegetProfile() 方法中。您正在使用此方法 returning this.profile,相反,您应该 return 一个像这样的可观察对象:

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 对象。 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>