代码之家  ›  专栏  ›  技术社区  ›  Johan Rin

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

  •  0
  • Johan Rin  · 技术社区  · 6 年前

    我得到了一个 错误类型错误:无法读取未定义的属性“id” 当我导航到组件时。在调试代码之后,我发现我的错误在哪里,但我没有找到正确的方法来解决它。也许你能帮我?

    下面是我的.ts文件:

    @Component({
      selector: 'app-forum-thread',
      templateUrl: './forum-thread.component.html',
      styleUrls: ['./forum-thread.component.css']
    })
    export class ForumThreadComponent implements OnInit {
      @Input() theme: Theme;
      threads: Observable<Thread[]>;
    
    constructor(
      private route: ActivatedRoute,
      private location: Location,
      private themeService: ThemeService,
      private threadService: ThreadService
    ) { }
    
    ngOnInit() {
      this.getTheme();
      this.getThreads();
    }
    
    getTheme(): void {
      this.themeService.getTheme(this.route.snapshot.paramMap.get('theme'))
        .subscribe(theme => this.theme = theme);
    }
    
    // Error caused by this method..
    getThreads(): void {
      this.threads = this.threadService.getThreads(this.theme.id);
    }
    

    以及相应的.html文件:

    <div *ngIf="theme">
      <h2>{{ theme.name | uppercase }}</h2>
    
      <table class="Threads">
         <tr>
           <th>Id</th>
           <th>Date</th>
           <th>Title</th>
           <th>Views</th>
           <th>Thanks</th>
           <th>Comments</th>
         </tr>
         <tr *ngFor="let thread of threads | async">
           <a routerLink="/forum-message/{{theme._id}}/{{thread._id}}">
             <td><span class="badge">{{thread._id}}</span></td>
           </a>
           <td>{{thread.createdAt | date}}</td>
           <td>{{thread.title}}</td>
           <td>{{thread.numberOfViews}}</td>
           <td>{{thread.numberOfThanks}}</td>
           <td>{{thread.numberOfComments}}</td>
         </tr>
       </table>  
     </div>
    

    我试图再次调用路由快照,结果成功了。 但我不喜欢两次调用路由快照,所以也许还有其他方法?

    getThreads(): void {
      this.threads = this.threadService.getThreads(
        this.route.snapshot.paramMap.get('theme'));
    }
    

    提前谢谢你的帮助!

    2 回复  |  直到 6 年前
        1
  •  0
  •   bc1105    6 年前

    ngOnInit block,您正在异步运行两个函数,因此 theme 查找 getThreads 将未定义。你需要等到主题设定好。

    getTheme(): void {
      this.themeService.getTheme(this.route.snapshot.paramMap.get('theme'))
        .subscribe(theme => {
          this.theme = theme;
          this.getThreads(theme.id);
        });
    }
    

    变化 获取线程 到:

    getThreads(themeId): void {
      this.threads = this.threadService.getThreads(themeId);
    }
    
        2
  •  0
  •   Johan Rin    6 年前

    我终于改了密码 this.route.snapshot.paramMap.get('theme'); 在一个 const 在像这样调用我的函数之前:

    ngOnInit() {
      const id = this.route.snapshot.paramMap.get('theme');
    
      this.themeService.getTheme(id)
        .subscribe(theme => {
          this.theme = theme,
          this.getThreadsTheme(theme._id)
        });
    }