2016-09-20 106 views
3

我想要的值從我的組件ImageDetail綁定到組件ImageComment像異步結合angular2

ImageDetailHtml:

<image-comment [photo]="photo"></image-comment> 

ImageCommentComponent:

export class ImageCommentComponent { 
    @Input('photo') photo: Photo; 

,並顯示該值代入我的ImageCommentHtml :

<h3>{{user.userName}}</h3> 
    <h4>{{photo.title}}</h4> 
    <p>{{photo.description}}</p> 

問題是,構建ImageCommentHtml後,照片的數據被加載,我沒有得到值。任何想法orexamples我可以如何解決這個異步問題?我非常努力,沒有任何工作。

以後有機會加載子組件嗎?

**更新** 試過的解決方案:

<image-comment *ngIf="photo" [photo]="photo"></image-comment> 

,它仍然無法正常工作。我加了幾個伐木工人:

ngAfterViewChecked() { 
    console.log("After view checked: " + 'photo', this.photo) 
    } 

    ngOnInit() { 
    console.log("On Init: " + 'photo', this.photo) 
    } 

,其結果是:

On Init: photo Photo {} 
image-comment.component.ts:42 After view checked: photo Photo {} 
image-comment.component.ts:42 After view checked: photo Photo {} 
image-comment.component.ts:42 After view checked: photo Photo {} 
image-comment.component.ts:42 After view checked: photo Photo {} 
image-comment.component.ts:42 After view checked: photo Photo {} 
image-comment.component.ts:42 After view checked: photo Photo {} 
image-comment.component.ts:42 After view checked: photo Photo {} 
image-comment.component.ts:42 After view checked: photo Photo {} 
image-comment.component.ts:42 After view checked: photo Photo {} 
image-comment.component.ts:42 After view checked: photo Object {photoId: 4, photoName: "#love", photoTitle: "me", photoDescription: null, imageName: "Unbenannt.PNG"…} 

所以還是加載到後期:( ImageDetailComponent

//COMPONENTS 
    import {Component} from '@angular/core'; 
    import {Router, ActivatedRoute, Params} from '@angular/router'; 
    import {ImageCommentComponent} from './image-comment.component.ts' 
    //SERVICES 
    import {UserService} from '../services/user.service'; 
    import {PhotoService} from '../services/photo.service'; 
    //MODELS 
    import {User} from '../models/user.model'; 
    import {Photo} from '../models/photo.model'; 
    //SETTINGS 
    import {LocalStorageSettings} from '../properties/localstorage.properties'; 

    @Component({ 
     selector: 'image-detail', 
     templateUrl: 'app/components/image-detail.component.html', 
     providers: [PhotoService,UserService] 
    }) 

    export class ImageDetailComponent { 
     photo: Photo = new Photo(); 
     like: string; 
     user: User; 
     imageUrl: string; 



     constructor(
     private photoService: PhotoService, 
     private userService: UserService, 
     private route: ActivatedRoute 
    ) { 
     let photoId: any; 
     this.route.params.forEach((params: Params) => { 
      photoId = +params['id']; 
     }); 
     this.photoService.getPhotoByPhotoId(photoId).subscribe(
      photo => { 
      this.photo = JSON.parse(JSON.parse(JSON.stringify(photo))._body); 
      this.imageUrl = "http://localhost:8080/images/" + this.photo.imageName; 

      this.userService.getUserByName(`${LocalStorageSettings.getLocalUsername}`).subscribe(
       user => { 
       this.user = JSON.parse(JSON.parse(JSON.stringify(user))._body); 
       if(this.user.likedPhotoList.filter(photo => photo.photoId == this.photo.photoId)[0]) { 
        this.like="Unlike"; 
       } else { 
        this.like="Like"; 
       } 
       }, 
       error => console.log(error) 
      ) 
      }, 
      error => console.log(error) 
     ) 
     } 

     goBack() { 
     window.history.back(); 
     } 

     likeDisplay() { 
     if(this.like == "Like") { 
      this.like = "Unlike"; 
      this.user.likedPhotoList.push(this.photo); 
      this.photo.likes+=1; 
      this.userService.updateUser(this.user).subscribe(); 
      this.photoService.updatePhoto(this.photo).subscribe(); 
     } else { 
      this.like = "Like"; 
      for(let i = 0; i < this.user.likedPhotoList.length; i++) { 
      if(this.user.likedPhotoList[i].photoId == this.photo.photoId) { 
       this.user.likedPhotoList.splice(i,1); 
      } 
      } 

      this.photo.likes-=1; 
      this.userService.updateUser(this.user).subscribe(); 
      this.photoService.updatePhoto(this.photo).subscribe(); 
     } 
     } 
    } 

ImageDetailHtml:

<div class="pusher"> 
    <div class="ui inverted vertical segment"> 
    <div class="ui text container"> 
     <div class="center aligned"> 
     <img src="{{imageUrl}}" class="ui image centered" /> 
     </div> 
     <br> 
     <div class="ui grid"> 
      <div class="left floated six wide column" style="cursor:pointer; color:grey;"> 
      <span (click)="goBack()"><i class="long arrow left icon">Back</i> </span> 
      </div> 
      <div class="left floated ten wide column right aligned" style=" color:grey;"> 
      <i class="thumbs outline up icon"></i>{{photo.likes}} &nbsp;&nbsp;&nbsp; 
      <a style="cursor: pointer" (click)="likeDisplay()">{{like}}</a> 
      </div> 
     </div> 
    </div> 
    </div> 
</div> 
<image-comment *ngIf="photo" [photo]="photo"></image-comment> 

ImageCommentComponent:

//COMPONENTS 
import {Component} from '@angular/core'; 
//MODELS 
import {User} from '../models/user.model'; 
import {Photo} from '../models/photo.model'; 
// SERVICES 
import {UserService} from '../services/user.service'; 
import {AddPhotoService} from '../services/add-photo.service'; 
import {UploadPhotoService} from '../services/upload-photo.service'; 
// SETTINGS 
import {LocalStorageSettings} from '../properties/localstorage.properties'; 

@Component({ 
    selector: 'add-photo', 
    providers: [UploadPhotoService, AddPhotoService], 
    templateUrl: 'app/components/add-photo.component.html' 
}) 
export class AddPhotoComponent { 
    newPhoto: Photo = new Photo(); 
    photoAdded: boolean = false; 
    user: User; 

    constructor (
    private uploadPhotoService: UploadPhotoService, 
    private addPhotoService: AddPhotoService, 
    private userService: UserService 
) {} 

    onSubmit() { 
    var userName: string = localStorage.getItem(`${LocalStorageSettings.LOCAL_STORAGE_USERNAME}`); 
    this.userService.getUserByName(userName).subscribe(
     user => { 
     this.user = JSON.parse(JSON.parse(JSON.stringify(user))._body); 
     console.log(this.user); 
     this.newPhoto.user = this.user; 
     this.addPhotoService.sendPhoto(this.newPhoto).subscribe(
      data => { 
      this.photoAdded = true; 
      this.newPhoto = new Photo(); 
      }, 
      error => console.log(error) 
     ) 
     }, 
     error => console.log(error) 
    ) 
    } 
} 

ImageComponentHtml:

<div class="ui text container"> 
    <h3>{{user.userName}}</h3> 
    <h4>{{photo?.title}}</h4> 
    <p>{{photo?.description}}</p> 

    <div class="ui comments"> 
    <h3 class="ui dividing header">Comments</h3> 

    <div class="comment" *ngFor="let comment of photo.commentList"> 
     <div class="ui grid"> 
     <div class="two wide column"> 
      <img src="http://localhost:8080/pic/avatar1.png" class="ui image tiny"> 
      <span class="author">{{photoComment.userName}}</span> 
     </div> 
     <div class="fourteen wide column"> 
      <div class="ui blue message"> 
      <div class="content"> 
       <div class="text"> 
       {{photoComment.content}} 
       </div> 
      </div> 
      </div> 
     </div> 
     </div> 
    </div> 
    <br> 
    <div class="ui grid"> 
     <div class="two wide column"> 
     <img src="http://localhost:8080/pic/avatar1.png" class="ui image tiny"> 
     <span class="author">{{user.userName}}</span> 
     </div> 
     <div class="fourteen wide column"> 
     <form class="ui form" (ngSubmit)="onSubmit()" #commentForm="ngForm"> 
      <div class="field"> 
      <textarea #words rows="3" placeholder="Add a comment" required [(ngModel)]="photoComment.content" name="photoCommentContent"></textarea> 
      </div> 
      <button type="submit" class="ui red button">Comment</button> 
     </form> 
     </div> 
    </div> 
    </div> 
</div> 
+1

您應該檢查照片的數據並確保數據已加載。 –

回答

1

你可以使用*ngIf指令變量只photo後作出ImageCommentComponent加載接收數據,而不是之前:

<image-comment *ngIf="photo" [photo]="photo"></image-comment> 

編輯:

問題在於你ImageDetailComponent - 你初始化變量photo

photo: Photo = new Photo(); 

您應該只聲​​明,就像這樣:

photo: Photo; 

這樣,photo值將是undefinedImageCommentComponent將不會加載直到photo收到數據。

+0

感謝您的快速回復!仍然不起作用:(我添加了瀏覽器的日誌以及這兩個組件和htmls的代碼。 – Keshtocal

+0

@Keshtocal我發現錯誤,並解釋瞭如何解決它,再次檢查我的帖子。 –

+0

嘿Stefant,謝謝!現在我得到OnInit的值! :))) 非常感謝!現在,我只需要找出爲什麼我將它作爲「對象」而不是「照片」 - 模型。 – Keshtocal