我在我的元件中創建了一個我訂閱的服務,但是當我使用ngFor時,div根本不渲染。
Component.TS檔案
import { Component, OnInit } from '@angular/core'; import {FormBuilder, Validators} from '@angular/forms'; import { PlansService } from 'src/app/services/plans.service'; interface JobType { value: string; viewValue: string; } interface WorkEnv { value: string; viewValue: string; } @Component({ selector: 'app-post-job', templateUrl: './post-job.component.html', styleUrls: ['./post-job.component.css'] }) export class PostJobComponent implements OnInit { jobTypes: JobType[] = [ {value: 'type-0', viewValue: '全职'}, {value: 'type-1', viewValue: '兼职'}, {value: 'type-2', viewValue: '自由职业'}, ]; workEnvs: WorkEnv[] = [ {value: 'type-0', viewValue: '远程'}, {value: 'type-1', viewValue: '混合'}, {value: 'type-2', viewValue: '现场'}, ]; jobForm = this.fb.group({ jobTitle: this.fb.group({ title: ['', [Validators.required, Validators.minLength(2), Validators.pattern('^[_A-z0-9]*((-|\s)*[_A-z0-9])*$')]], jobType: ['', [Validators.required]] }), }) plans: any; constructor(private fb: FormBuilder, private service:PlansService) { } ngOnInit(): void { this.service.getPlans() .subscribe(response => { this.plans = response; console.log(response); }); } // Getter method to access formcontrols get myForm() { return this.jobForm.controls; } // Submit Registration Form // onSubmit() { // this.submitted = true; // if(!this.jobForm.valid) { // alert('Please fill all the required fields to create a super hero!') // } else { // console.log(this.jobForm.value) // } // } }
Component.html檔案
<div class="subscription-container" > <div class="card" *ngFor="let plan of plans " > <h1>{{plan.title}}</h1> </div> </div>
資料在我的console.log中顯示,但在卡片上根本沒有渲染。請幫忙,謝謝!
我嘗試在ts檔案中新增了一個虛擬數組,並將其列印到控制台日誌中,但仍然沒有在div中渲染。
您可以非同步載入您的計劃。
建立一個可觀察對象
public plans$: Observable<any>
#分配您的訂閱
this.plans$ = this.service.getPlans();
在您的HTML中有條件地渲染