我在 Angular 6 中有以下服务:
@Injectable()
export class LoginService {
constructor(private http: HttpClient) { }
login(): Observable<boolean> {
var url = `${environment.baseAPIUrl}${environment.loginUrl}`;
return this.http.get<boolean>(url);
}
}
Run Code Online (Sandbox Code Playgroud)
我从我的组件调用它:
@Component({
selector: 'bpms-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
constructor(private loginService: LoginService) { }
ngOnInit() {
}
login() {
var self = this;
self.loginService.login();
}
}
Run Code Online (Sandbox Code Playgroud)
为什么它不发送我的请求?
屏幕上显示的值是正确的,但我在日志中收到此错误:ERROR TypeError: Cannot read property 'name' of undefined。
我用 '?' 尝试了几种方法 像这样:
[(ngModel)]="customer?.name"但不起作用,那么我需要帮助:)
在服务中:
getCustomer(name:string){
let url = `http://localhost:8081/api/customer/${name}`;
return this.http.get<Customer>(url);
}
Run Code Online (Sandbox Code Playgroud)
在组件的 .ts 中:
customer: Customer;
this.customerService.getCustomer(this.pName)
.subscribe(
(data) =>{
this.customer = data['customer'];
},
err =>{
console.log('getCustomer failed');
}
);
Run Code Online (Sandbox Code Playgroud)
在模板中:
<input type="text" class="form-control" id="myname" required [(ngModel)]="customer.name" name="myname">
Run Code Online (Sandbox Code Playgroud)
但这不行。
你有想法吗 ?
谢谢,
我有一个如下所示的基本形式。我调用一个 API 来获取用户的个人信息,我想用适当的值填充表单字段。我一直在尝试使用,patchValue但我无法让它工作。
<form (ngSubmit)="onSubmit" class="example-form" [formGroup]="firstFormGroup" #registerForm="ngForm">
<mat-form-field class="example-full-width">
<input matInput placeholder="Company" formControlName="company" required autofocus>
<mat-error *ngIf="firstFormGroup.get('company').hasError('required')">
Company name is
<strong>required</strong>
</mat-error>
</mat-form-field>
<table class="example-full-width" cellspacing="0">
<tr>
<td>
<mat-form-field class="example-full-width">
<input matInput placeholder="First name" formControlName="first_name" required>
<mat-error *ngIf="firstFormGroup.get('first_name').hasError('required')">
First name is
<strong>required</strong>
</mat-error>
</mat-form-field>
</td>
<td>
<mat-form-field class="example-full-width">
<input matInput placeholder="Last Name" formControlName="last_name" required>
<mat-error *ngIf="firstFormGroup.get('last_name').hasError('required')">
Last name is
<strong>required</strong>
</mat-error>
</mat-form-field>
</td>
</tr>
<tr>
<td>
<mat-form-field class="example-full-width">
<input matInput placeholder="Email" formControlName="email" required>
<mat-error *ngIf="firstFormGroup.get('email').hasError('email') && !email.hasError('required')"> …Run Code Online (Sandbox Code Playgroud) 我从 MySQL 数据库获取用户列表以<mat-table>使用dataSource属性显示它:
以下是 typescript 方法getUnitData(),我将 dataSource 值设置为从 PHP 脚本返回的 JSON 数组:
export class RegistrationComponent implements OnInit {
dataSource: MatTableDataSource<units>;
@ViewChild(MatPaginator) paginator: MatPaginator;
@ViewChild(MatSort) sort: MatSort;
constructor(private auth: AuthApiService) { }
ngOnInit() {
this.dataSource.paginator = this.paginator;
this.dataSource.sort = this.sort;
}
applyFilter(filterValue: string){
this.dataSource.filter = filterValue.trim().toLowerCase();
if(this.dataSource.paginator)
{
this.dataSource.paginator.firstPage();
}
}
getUnitData(){
this.auth.getUnitDataService().subscribe(
(data)=>
{
this.dataSource = new MatTableDataSource(data);
},
(error)=>
{
}
)
}
}
Run Code Online (Sandbox Code Playgroud)
这是来自的主要方法AuthApiService:
getUnitDataService(){
if(this.checkIsLogin){
this.headerOptions.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
return …Run Code Online (Sandbox Code Playgroud) 我正在使用 Angular 6 和 ngx-translate。在不弄乱主题的情况下切换到 rtl 的唯一方法是<html dir="rtl">在 index.html 中。
在component.ts:
switchLanguage(language: string) {
this.translate.use(language);
localStorage.setItem('lang', JSON.stringify(language));
}
Run Code Online (Sandbox Code Playgroud)
如何添加dir="rtl"到<html>if language === "ar",否则将其删除?
我使用 ng-container 迭代列表并创建组件
<ng-container *ngFor="let f of optionsList; let i = index;">
<!-- component-->
<app-component #fieldcmp *ngIf="isAppComponent(f)" ></app-field>
<!--another components-->
<app-anoter-component1 *ngIf="isAnotherComponent1(f)"> </app-anoter-component1>
...
<app-anoter-componentn *ngIf="isAnotherComponentn(f)"> </app-anoter-componentn>
</ng-container>
Run Code Online (Sandbox Code Playgroud)
我想列出 ng-container 中的 References 组件。
我尝试使用 @ViewChildren('#fieldcmp') fieldsList: QueryList; 和@ContentChildren('#fieldcmp') fieldsList: QueryList; 在父组件内部,但如果我尝试在 ngafterViewInit 中访问,我将没有任何元素
ngAfterViewInit() {
this.fieldsList.forEach((child) => { /* some logic....*/});
}
Run Code Online (Sandbox Code Playgroud)
有人可以帮助我吗?谢谢
-----------更新---------------
使用@ViewChildren('fieldcmp') 修复后,我有一个ElementRef列表,而不是我的 AppComponent。我用它和所有的工作
this.filedsList
.forEach((child) => { atLeastOneRequired = atLeastOneRequired || (<ReusableFieldComponent> child).isRequired();
});
Run Code Online (Sandbox Code Playgroud)
谢谢你的帮助
当我尝试从我的 api 获取数据时,我在我的 angular 6 项目中收到此错误。这是我的 api json 文件;
{"data":
[{"category_name":"Women Ready Made","slug":null,"image_url":"education.jpg","products":
[{"productName":"Kampala
Shorts","description":"Beautiful Handwoven Kampala Shorts","imageUrl":"C:\\codes\\Tradsonline\\img\\image1.jpg","price":2500,"discount":10},{"productName":"Flowing White Agbada","description":"Flowing white agbada with beautiful design.","imageUrl":"C:\\codes\\Tradsonline\\img\\image3.jpg","price":22000,"discount":15}]},{"category_name":"Men's Ready Made","slug":null,"image_url":"education.jpg","products":[{"productName":"Ankara Jacket","description":"Ankara Jackets with pockets.","imageUrl":"C:\\codes\\Tradsonline\\img\\image2.jpg","price":5000,"discount":15},{"productName":"Women Ankara Gown","description":"Women Ankara gown with beautiful design.","imageUrl":"C:\\codes\\Tradsonline\\img\\image4.jpg","price":8000,"discount":0}]},{"category_name":"Ankara Gowns","slug":null,"image_url":"education.jpg","products":[]}]}
Run Code Online (Sandbox Code Playgroud)
这是我的服务
getCategories(): Observable<Category[]> {
return this.http.get(this.base_url + 'categories')
.pipe(map(res => {
return res.data; //this is where the error happens
}));
Run Code Online (Sandbox Code Playgroud)
这是我对我的服务的进口
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Product } from '../models/product';
import { …Run Code Online (Sandbox Code Playgroud) HTML 是在我获取文件名的地方编写的,但我想摆脱文件扩展名,并将文件存储在数组中并在 UI 中访问它们。
<div class="myReadingListContainer">
<div class="readingList">
My Reading List
</div>
<div class="myReadingList">
<div class="uploadWrap">
<input type="file" #file (change)="onChange(file.files)" class="fileUploadInput" />
<div class="innerText">
<img src="assets/img/my_reading_list/Add.svg" class="addIcon">
<h6 class="addFile">Add Files</h6>
</div>
</div>
<div *ngFor="let file of fileList">
<div class="selectedFile">
<div class="documentName">
{{file.name}}
</div>
<span *ngIf="file.type === 'application/pdf'">
<img src="assets/img/my_reading_list/PDF.svg" class="fileTypeImage">
</span>
<span *ngIf="file.type === 'application/vnd.ms-excel'">
<img src="assets/img/my_reading_list/Excel.svg" class="fileTypeImage">
</span>
<div class="readingStatus">
20/35 Pages
</div>
<div class="progress">
<div class="progressBar"></div>
</div>
</div>
</div>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
打字稿文件是这样写的。由于我是 Angular 6 的新手,非常感谢任何帮助,提前致谢
import { Component, …Run Code Online (Sandbox Code Playgroud) 我的 Angular 项目是在 Angular 5 中创建的,并且已经使用该版本大约 6 个月左右。昨天我升级到了 Angular 6,在修复了我的所有rxjs引用并编译了应用程序以确保一切正常运行之后,我意识到在运行时保存更改ng serve以及ng test没有刷新我的浏览器或识别任何更改,直到我杀死我的ng serve并开始再来一遍。
我似乎在任何地方都找不到任何答案;有没有其他人遇到过这个问题,我可以提供我的项目的任何部分来帮助找到解决方案吗?
编辑:我在 Linux/Ubuntu 18.04 上运行
angular6 ×10
angular ×8
typescript ×4
angular5 ×1
bootstrap-4 ×1
datasource ×1
forms ×1
httpclient ×1
jasmine ×1
javascript ×1
ng-container ×1
ngfor ×1
upgrade ×1
viewchild ×1