我认为这是一个相当简单的设置。我在配置文件输入组件中创建用户配置文件。然后在提交表单并创建用户之后,我想将用户发送到profile-img-upload组件以添加照片。我的理解是,通过将创建的配置文件保存到配置文件服务中,然后在img-upload组件中调用该配置文件,这是有意义的。但我错过了一些东西,因为当我到达img-upload组件 console.log(this.profile)时,配置文件始终为null。
我觉得我在这里误解了订阅和观察的核心内容。我想要做的就是在第一个组件上创建一个Profile对象,然后将创建的Profile传递给第二个组件,然后才能上传照片并将其分配给Profile。
有人可以帮我理解我在这里缺少的东西吗?
个人资料-input.component
import...
@Component({
moduleId: module.id,
selector: 'my-profile-input',
templateUrl: 'profile-input.template.html',
directives: [REACTIVE_FORM_DIRECTIVES]
})
export class ProfileInputComponent implements OnInit {
@Output() profile: Profile;
profile: Profile = null;
constructor(private formBuilder:FormBuilder,
private profileSrevice: ProfileService,
private errorService: ErrorService,
private router: Router,
private route: ActivatedRoute) {}
onSubmit() {
const profile: Profile = new Profile(
this.profileForm.value.first_name,
this.profileForm.value.last_name
);
this.profileSrevice.addProfile(profile)
.subscribe(
data => {
console.log('what comes back from addProfile is: ' + JSON.stringify(data));
this.profileSrevice.profiles.push(data);
// The line below will superceded the one above.
this.profileSrevice.pushData(data);
},
error => this.errorService.handleError(error)
);
this.router.navigate(['profile-img-upload', {myProfile: this.profile}]);
}
profile.service.ts
import...
@Injectable()
export class ProfileService {
pushedData = new EventEmitter<Profile>();
pushData(value: Profile) {
this.pushedData.emit(value);
console.log('value in service is ');
console.log(value);
}
}
个人资料-IMG-upload.component.ts
import...
@Component({
moduleId: module.id,
selector: 'my-profile-img-upload',
templateUrl: 'profile-img-upload.template.html',
directives: [ ROUTER_DIRECTIVES, FILE_UPLOAD_DIRECTIVES, NgClass, NgStyle, CORE_DIRECTIVES, FORM_DIRECTIVES ],
providers: [AWSUploadService, UploadFileService]
})
export class ProfileImgUploadComponent implements OnInit {
@Input() myProfile: Profile;
profile: Profile;
constructor(private uploadFileService: UploadFileService,
private route: ActivatedRoute,
private profileService: ProfileService,
private errorService: ErrorService) {
this.filesToUpload = [];}
ngOnInit() {
this.profileService.pushedData.subscribe(
(value: Profile) => this.profile
);
console.log("this.profile in img upload is");
console.log(this.profile);
}
}
答案 0 :(得分:0)
您必须将引用订阅返回的数据的代码移动到订阅回调中。当数据从可观察的
到达时,将调用此回调 ngOnInit() {
this.profileService.pushedData.subscribe(
(value: Profile) => {
this.profile = value;
console.log("this.profile in img upload is");
console.log(this.profile);
});
}
}
答案 1 :(得分:0)