我有一个我认为是相当简单的设置。我正在配置文件输入组件中创建用户配置文件。然后在提交表单并创建用户后,我想将用户发送到 profile-img-upload 组件以添加照片。我的理解是,通过将创建的配置文件保存到配置文件服务中,然后在 img-upload 组件中调用该配置文件来完成这是有意义的。但是我遗漏了一些东西,因为当我到达 img-upload 组件console.log(this.profile)时,配置文件始终为空。
我觉得我在这里误解了订阅和可观察的一些非常核心的东西。我要做的就是在第一个组件上创建一个 Profile 对象,然后将创建的 Profile 传递给第二个组件,然后才能上传照片并将其分配给 Profile。
有人可以帮我理解我在这里缺少什么吗?
配置文件输入组件
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}]);
}
配置文件.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);
}
}
profile-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);
}
}