私はかなりシンプルな設定だと思っていました。プロファイル入力コンポーネントにユーザープロファイルを作成しています。その後、フォームが送信され、ユーザーが作成された後、profile-img-uploadコンポーネントにユーザーを送信して写真を追加します。私が理解しておくことは、作成したプロファイルをプロファイルサービスに保存し、img-uploadコンポーネントでそのプロファイルを呼び出すことで意味をなさないことです。しかし、何かが欠けているのは、img-uploadコンポーネントconsole.log(this.profile)のプロファイルは常にnullです。Angular2サブスクリプションが常にヌルになる
サブスクリプションとオブザーバビリティに関する非常にコアなものを誤解しているような気がします。私がしたいのは、最初のコンポーネントにProfileオブジェクトを作成し、作成したProfileを2番目のコンポーネントに渡して、写真をアップロードしてそれをプロファイルに割り当てることだけです。
私はここで何が欠けているのか理解してもらえますか?
プロファイル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);
}
}
これを試してみましたが、実際にログが「img uploadのthis.profile」というログをコンソールに表示することはありません。 – JasonPerr
コンソールに最後に出力される値は**サービスの**値ですプロファイルオブジェクト(profile.service pushDataメソッドから取得) – JasonPerr
実行時に実際に何が起こっているのかをいくつかのコードスニペットから得るのは難しいです。コールバックが呼び出された後にのみデータが利用可能であることに注意する必要があります。 –