无法将从订阅方法接收的值存储在模板变量中。
照片细节成分
import { Component, OnInit, Input } from "@angular/core";
import { PhotoSevice } from "../photo.service";
import { Photo } from "src/app/model/photo.model";
@Component({
selector: "app-photo-detail",
templateUrl: "./photo-detail.component.html",
styleUrls: ["./photo-detail.component.css"]
})
export class PhotoDetailComponent implements OnInit {
url: string;
constructor(private photoService: PhotoSevice) {
this.photoService.photoSelected.subscribe(data => {
this.url = data;
console.log(this.url);
});
console.log(this.url);
}
ngOnInit() {
}
}
外部console.log给出了未定义的内容,并且视图中未呈现任何内容,但是在subscibe方法内部,我可以看到该值。因此,如何在视图中显示它?
照片组件
import { Component, OnInit } from "@angular/core";
import { ActivatedRoute, Params, Router } from "@angular/router";
import { FnParam } from "@angular/compiler/src/output/output_ast";
import { AlbumService } from "../service/album.service";
import { Photo } from "../model/photo.model";
import { PhotoSevice } from "./photo.service";
@Component({
selector: "app-photos",
templateUrl: "./photos.component.html",
styleUrls: ["./photos.component.css"]
})
export class PhotosComponent implements OnInit {
selectedAlbumId: string;
photoList: Photo[] = [];
photoSelected: Photo;
isLoading: Boolean;
constructor(
private rout: ActivatedRoute,
private albumService: AlbumService,
private router: Router,
private photoService: PhotoSevice
) { }
ngOnInit() {
this.isLoading = true;
this.rout.params.subscribe((params: Params) => {
this.selectedAlbumId = params["id"];
this.getPhotos(this.selectedAlbumId);
});
}
getPhotos(id: string) {
this.albumService.fetchPhotos(this.selectedAlbumId).subscribe(photo => {
this.photoList = photo;
this.isLoading = false;
});
}
displayPhoto(url: string, title: string) {
console.log(url);
this.photoService.photoSelected.emit(url);
this.router.navigate(["/photo-detail"]);
}
}
[请向我解释这是如何工作的以及如何解决它,以便我可以在模板视图中存储和显示从订阅和asyncdhonours调用接收的值。