从后端初始化表单值

时间:2017-01-25 09:10:46

标签: angular angular2-forms angular2-services angular2-observables

我有以下服务来获取数据。我正在按预期获得数据

export class UserService {
user: User
    private userSource = new Subject<User>();
    currentUser = this.userSource.asObservable();

constructor(http: Http){}

resolve(route: ActivatedRouteSnapshot){
      return this.http.get('/getUserData')
        .map(output => {
            console.log("IN RESOLVE. OUTPUT = ");
            console.log(output as User);        // Getting output here as expected
            return output as User;
        })
 }}

用户模型

export clsss User {
constructor(public Basic: {mob: string; email: string},
        public other: {abc: string; xyz: string  }) {}

BasicComponent.ts

export class BasicComponent implements OnInit {
basicForm: FormGroup;
user: User;

constructor(private fb: FormBuilder, public userService: UserService) { }

ngOnInit() {
        this.userService.currentUser.subscribe(
            result => {
              console.log(result)
             this.user = result
            })
        this basicForm = this.fb.group({
              mob: [this.user.mob, Validators.compose([Validators.required, Validators.minLength(10)],
              email: ['', Validators.compose([Validators.required, EmailValidator.isValidMailFormat])]
        })
}}

我希望预填充这些值。但是user对象显示undefined。 这是最小的代码。我还有其他组件,例如BasicComponent,每个组件都有forms。我已经包含了所有依赖项和&amp;其他声明。它工作正常,除了我没有在Formbuilder

中获取用户对象

我缺少什么?

2 个答案:

答案 0 :(得分:0)

export class BasicComponent implements OnInit {
basicForm: FormGroup;
user: User;

constructor(private fb: FormBuilder, public userService: UserService) { }

ngOnInit() {
        let __self = this;
        this.userService.currentUser.subscribe(result => {
             console.log(result)
             __self.user = result;
             __self contact = __self.fb.group({
                    mob: [__self.user.mob, Validators.compose([Validators.required, Validators.minLength(10)],
                    email: ['', Validators.compose([Validators.required, EmailValidator.isValidMailFormat])]
                });
            });
}}

答案 1 :(得分:0)

尝试这种方法

 ngOnInit() {
        // Build the form
        this.basicForm = this.fb.group({
            'business_name' : ['', Validators.required],
            'email'   : ['', Validators.required],
        });
        // Fetch data for the view
         this.userService.currentUser.subscribe(
            result => {
              console.log(result)
             this.user = result

             this.basicForm.setValue({
                business_name: response.data.business.business_name,
                email: response.data.business.email
            });


        })
    }