首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >不将JSON响应映射到嵌套接口

不将JSON响应映射到嵌套接口
EN

Stack Overflow用户
提问于 2020-06-18 12:50:19
回答 2查看 379关注 0票数 0

我的JSON响应(来自ASP.NET核心Web )如下所示:

代码语言:javascript
复制
[
  {
    "pilot": {
      "firstName": "TEST",
      "lastName": "LAST",
      "assignedFlight": "O_FLIGHT"
    }
  },
  {
    "pilot": {
      "firstName": "First",
      "lastName": "Last",
      "assignedFlight": "M_FLIGHT"
    }
  }
]

我的TypeScript接口看起来像:

pilot.ts

代码语言:javascript
复制
export interface Pilot {
    firstName: string;
    lastName: string;
    assignedFlight: string;
}

commitment.ts

代码语言:javascript
复制
import { Pilot } from './pilot';

export interface Commitment {
    pilot: Pilot;
}

在我的commitments.service.ts

代码语言:javascript
复制
@Injectable({
  providedIn: 'root'
})
export class CommitmentsService {

  private commitmentsApiUrl = 'http://localhost:55012/commitments';

  constructor(private http: HttpClient) { }

  getCommitments(): Observable<Commitment[]> {
    return this.http.get<Commitment[]>(this.commitmentsApiUrl).pipe(tap(ev => console.log(ev)));
  }
}

最后,我赞同在我的组件中可观察到的内容:

代码语言:javascript
复制
@Component({
  selector: 'app-commitments',
  templateUrl: './commitments.component.html',
  styleUrls: ['./commitments.component.css']
})
export class CommitmentsComponent implements OnInit {

  commitments: Commitment[];

  constructor(private commitmentsService: CommitmentsService) { }

  ngOnInit(): void {
    this.commitmentsService.getCommitments().subscribe(commitments => this.commitments = commitments);
    console.log(this.commitments); /* Undefined here??? */
  }
}

对于我的生活,我不明白为什么当涉及嵌套接口时没有映射JSON。组件中的this.commitments显示undefined。我已经通过JSON验证器/linter运行了JSON,它表明它是有效的。我知道答案很简单,我对此视而不见。有什么想法吗?谢谢!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-06-18 12:53:39

界面看起来很好。this.commitments是异步分配的。当您执行控制台日志时,变量this.commitments仍未定义。您需要将console.log()移动到订阅中。

代码语言:javascript
复制
this.commitmentsService.getCommitments().subscribe(
  commitments => {
    this.commitments = commitments;
    console.log(this.commitments);
  },
  error => {
    // always good practice to handle HTTP errors
  }
);

有关如何访问异步数据here的更多详细信息。

票数 2
EN

Stack Overflow用户

发布于 2020-06-18 12:56:20

除非您的组件中绝对必须有this.commitments,否则不要。它会使事情变得更复杂,使用异步管道代替:

代码语言:javascript
复制
// component
@Component({
  selector: 'app-commitments',
  templateUrl: './commitments.component.html',
  styleUrls: ['./commitments.component.css']
})
export class CommitmentsComponent implements OnInit {
  commitments$ = this.commimentsService.getCommitments();
  constructor(private commitmentsService: CommitmentsService) { }
}

//template
<some-other-component [commitments]="commitments$ | async"></some-other-component>

所谓“让事情变得更复杂”,我的意思是说,您有很多事情需要自己考虑--管理订阅,确保this.commitments在从组件内部访问它时是最新的。

我开发的应用程序中,每个组件都创建了大量实例变量,这完全是为了上面编写的模式。它变得比你想象的要快得多。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62450377

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档