如何在Angularjs版本7中修复“模板解析错误”

时间:2019-02-15 11:17:30

标签: angularjs

我试图在项目联系人页面的反馈表单上将动画与进度微调器一起使用,并使用post()方法返回提交的反馈对象作为返回值,以简要显示提交的数据以确认表单提交给用户:

    enter code here// code for contact.component.ts
       import { FeedbackService } from './../services/feedback.service';
       import { Component, OnInit, ViewChild, Inject } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Feedback, ContactType } from '../shared/feedback';
import { flyInOut, expand } from '../animations/app.animation';

@Component({
  selector: 'app-contact',
  templateUrl: './contact.component.html',
  styleUrls: ['./contact.component.scss'],
  // tslint:disable-next-line:use-host-property-decorator
  host: {
    '[@flyInOut]': 'true',
    'style': 'display: block;'
    },
  animations: [
    flyInOut(),
    expand()
  ]
})
export class ContactComponent implements OnInit {
  @ViewChild('fform') feedbackFormDirective;
  submitted: boolean;
  feedbackForm: FormGroup;
  feedback: Feedback;
  contactType = ContactType;
  errMess: string;
  formErrors = {
    'firstname': '',
    'lastname': '',
    'telnum': '',
    'email': ''
  };

  validationMessages = {
    'firstname': {
      'required':      'First Name is required.',
      'minlength':     'First Name must be at least 2 characters long.',
      'maxlength':     'FirstName cannot be more than 25 characters long.'
    },
    'lastname': {
      'required':      'Last Name is required.',
      'minlength':     'Last Name must be at least 2 characters long.',
      'maxlength':     'Last Name cannot be more than 25 characters long.'
    },
    'telnum': {
      'required':      'Tel. number is required.',
      'pattern':       'Tel. number must contain only numbers.'
    },
    'email': {
      'required':      'Email is required.',
      'email':         'Email not in valid format.'
    },
  };
  constructor(private fb: FormBuilder,
    private feedbackService: FeedbackService,
    @Inject('BaseURL') public BaseURL) {
    this.createForm();
   }

  ngOnInit() {
  }

  createForm() {
    this.feedbackForm = this.fb.group({
      firstname: ['', [Validators.required, Validators.minLength(2), Validators.maxLength(25)] ],
      lastname: ['', [Validators.required, Validators.minLength(2), Validators.maxLength(25)] ],
      telnum: ['', [Validators.required, Validators.pattern] ],
      email: ['', [Validators.required, Validators.email] ],
      agree: false,
      contacttype: 'None',
      message: ''
    });
    this.feedbackForm.valueChanges
      .subscribe(data => this.onValueChanged(data));

    this.onValueChanged(); // (re)set validation messages now
  }

  onValueChanged(data?: any) {
    if (!this.feedbackForm) { return; }
    const form = this.feedbackForm;
    for (const field in this.formErrors) {
      if (this.formErrors.hasOwnProperty(field)) {
        // clear previous error message (if any)
        this.formErrors[field] = '';
        const control = form.get(field);
        if (control && control.dirty && !control.valid) {
          const messages = this.validationMessages[field];
          for (const key in control.errors) {
            if (control.errors.hasOwnProperty(key)) {
              this.formErrors[field] += messages[key] + ' ';
            }
          }
        }
      }
    }
  }

  onSubmit() {
    this.submitted = true;
    this.feedback = this.feedbackForm.value;
    console.log(this.feedback);
    this.feedbackService.submitFeedback(this.feedback)
      .subscribe(data => {
        this.feedback = data,
        // after 5s form becomes not submitted (visible)
        setTimeout(() => {
          this.submitted = false; }, 5000); },
      errmess => { this.feedback = null; this.errMess = <any>errmess; });
      this.feedbackFormDirective.resetForm();
    this.feedbackForm.reset({
      firstname: '',
      lastname: '',
      telnum: '',
      email: '',
      agree: false,
      contacttype: 'None',
      message: ''
    });
  }
}
 // code of contact.component.html
     <div class="container"
  fxLayout="column"
  fxLayoutGap="10px">

  <div fxFlex>
    <div>
        <h3>Contact Us</h3>
        <hr>
    </div>
  </div>

  <div fxFlex>
    <h3>Location Information</h3> 
    <div fxLayout="column" fxLayout.gt-sm="row">
      <div fxFlex="50" fxFlexOffset="20px">
        <h4>Our Address</h4>
        <address>
          121, Clear Water Bay Road<br>
          Clear Water Bay, Kowloon<br>
          HONG KONG<br>
          <i class="fa fa-phone"></i>: +852 1234 5678<br>
          <i class="fa fa-fax"></i>: +852 8765 4321<br>
          <i class="fa fa-envelope"></i>: 
                <a href="mailto:confusion@food.net">confusion@food.net</a>
        </address>
        <p></p>
        <div>
          <a mat-raised-button href="tel:+85212345678"><i class="fa fa-phone"></i> Call</a>
          <a mat-raised-button><i class="fa fa-skype"></i> Skype</a>
          <a mat-raised-button href="mailto:confusion@food.net"><i class="fa fa-envelope-o"></i> Email</a>
        </div>
        </div>
      <div fxFlex="40">
        <h4>Map of our Location</h4>
      </div>
    </div>
  </div>

  <div fxFlex fxFlexOffset="20px" class="form-size">
      <h3>Send us your Feedback</h3>
      <p>{{ feedbackForm.value | json }} {{ feedbackForm.status | json }}</p>



    <form novalidate [formGroup]="feedbackForm" #fform="ngForm" (ngSubmit)="onSubmit()">
      <p>
          <mat-form-field class="half-width">
              <input matInput formControlName="firstname" placeholder="First Name" type="text" required>
              <mat-error *ngIf="formErrors.firstname">{{formErrors.firstname}}</mat-error>
            </mat-form-field>
            <mat-form-field class="half-width">
              <input matInput formControlName="lastname" placeholder="Last Name" type="text" required>
              <mat-error *ngIf="formErrors.lastname">{{formErrors.lastname}}</mat-error>
            </mat-form-field>
          </p>
          <p>
            <mat-form-field class="half-width">
              <input matInput formControlName="telnum" placeholder="Tel. Number" type="tel" pattern="[0-9]*" required>
              <mat-error *ngIf="formErrors.telnum">{{formErrors.telnum}}</mat-error>
            </mat-form-field>
            <mat-form-field class="half-width">
              <input matInput formControlName="email" placeholder="Email" type="email" email required>
              <mat-error *ngIf="formErrors.email">{{formErrors.email}}</mat-error>
            </mat-form-field>
      </p>


        <table class="form-size">
          <td>
            <mat-slide-toggle formControlName="agree">May we contact you?</mat-slide-toggle>
          </td>
          <td>
            <mat-select placeholder="HowS?" formControlName="contacttype">
              <mat-option *ngFor="let ctype of contactType" [value]="ctype">
                {{ ctype }}
              </mat-option>
            </mat-select>
          </td>
          </table>
        <p>
          <mat-form-field class="full-width">
            <textarea matInput formControlName="message" placeholder="Your Feedback" rows=12></textarea>
          </mat-form-field>
        </p>
        <button type="submit" mat-button class="background-primary text-floral-white">Submit</button>
      </form>


  </div>

  <div [hidden]="feedback || errMess">

    <mat-spinner></mat-spinner>
  </div>
  <div fxflex  *ngif="feedback && submitted" @expand]=" ">   
    <mat-list >
      <h3>Your Submission</h3>
      <mat-list-item>
        <p matline="">First Name: {{feedback.firstname}} </p>
        <p matline="">Last Name: {{feedback.lastname}} </p>
        <p matline="">Tel. Number: {{feedback.telnum}}</p>
        <p matline="">Email: {{feedback.email}}</p>
        <p matline="">Contact You?: {{feedback.agree}}</p>
        <p matline="">How?: {{feedback.contacttype}}</p>
        <p matline="">Feedback: {{feedback.message}}</p>
      </mat-list-item>
    </mat-list>
  </div>
</div>

 // feedback.service.ts
    import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Feedback,ContactType } from '../shared/feedback';
import { map, catchError } from 'rxjs/operators';
import { ProcessHTTPMsgService } from './process-httpmsg.service';
import { baseURL } from '../shared/baseurl';
import { HttpClient, HttpErrorResponse, HttpHeaders,HttpSentEvent } from '@angular/common/http';

const HttpUploadOptions = {
  headers: new HttpHeaders({ "Content-Type": "application/json"  })
}
@Injectable({
  providedIn: 'root'
})
export class FeedbackService {

  constructor(private http: HttpClient, private processHTTPMsgService: ProcessHTTPMsgService) { }
  submitFeedback(feedback : Feedback):Observable<Feedback>{
    return this.http.post<Feedback>((baseURL + 'feedback'), feedback, HttpUploadOptions)
    .pipe(
      catchError(this.processHTTPMsgService.handleError)   
       );



  }
}
 // app.animation.ts

      import { trigger, state, style, animate, transition } from '@angular/animations';

export function visibility() {
    return trigger('visibility', [
        state('shown', style({
            transform: 'scale(1.0)',
            opacity: 1
        })),
        state('hidden', style({
            transform: 'scale(0.5)',
            opacity: 0
        })),
        transition('* => *', animate('0.5s ease-in-out'))
    ]);
}
export function flyInOut() {
    return trigger('flyInOut', [
        state('*', style({ opacity: 1, transform: 'translateX(0)'})),
        transition(':enter', [
            style({ transform: 'translateX(-100%)', opacity: 0 }),
            animate('500ms ease-in')
        ]),
        transition(':leave', [
            animate('500ms ease-out', style({ transform: 'translateX(100%)', opacity: 0}))
        ])
    ]);
}

export function expand() {
    return trigger('expand', [
        state('*', style({ opacity: 1, transform: 'translateX(0)' })),
        transition(':enter', [
            style({ transform: 'translateY(-50%)', opacity:0 }),
            animate('200ms ease-in', style({ opacity: 1, transform: 'translateX(0)' }))
        ])
    ]);
}

我实际上是在在线门户上执行angularjs分配的任务4,详细信息是-     任务4  在此任务中,您将使用动画和进度微调器,以及post()方法将返回已提交的反馈对象作为返回值的事实,以简要显示已提交的数据以确认向用户提交表单:

提交表单后,您应该隐藏表单并显示进度微调框,直到服务器响应以确认服务器端更新为止。有关更多详细信息,请参见下面的下一点。 回想一下在将数据保存到服务器的课程中,PUT请求如何返回我们订阅的可观察对象,然后使用返回的更新后的菜肴数据来更新dishdetail.component.ts中的菜肴对象。同样,当您执行post()时,反馈服务必须通过SubmitFeedback()方法返回提交后从服务器返回的反馈对象。然后,您可以在contact.component.ts中订阅它以获得返回的反馈对象。这确认了将反馈成功提交到服务器。 在上面的subscription()方法中从服务器获得确认后,您应该以视频中所示的格式显示来自返回的反馈对象的信息5秒钟。此后,您应该隐藏它,然后再次向用户显示空白表格,使他们能够再次提交反馈。提示:为此目的,请利用setTimeout()方法。 使用我们之前使用的扩展动画明智地将动画应用于表单提交的各个阶段。

0 个答案:

没有答案