程序不协调属性名称。我使用Input()函数并使用API。它应该显示来自我的api的所有推文。我尝试了很多其他的事情,比如交换名称,属性等等。。。我不能继续,因为它不起作用。有一种简单的方法可以解决此问题
tweet.component.html
<mat-card>
<mat-card-header>
<mat-card-title>
{{ tweet.name}}
</mat-card-title>
<mat-card-subtitle>added on {{ tweet.created | date: longDate }}</mat-card-subtitle>
</mat-card-header>
</mat-card>
tweet.component.ts
import { Component, OnInit, Input } from '@angular/core';
import { Tweet } from '../tweet.model';
import { TweetDataService } from 'src/app/tweet-data.service';
@Component({
selector: 'app-tweet',
templateUrl: './tweet.component.html',
styleUrls: ['./tweet.component.css']
})
export class TweetComponent implements OnInit {
@Input() public tweet: Tweet;
constructor() {
}
ngOnInit() {
}
}
tweet.model.ts
import { Reactie } from './reactie.model';
export class Tweet{
constructor(
private _name: string,
private _reacties = new Array<Reactie>(),
private _created = new Date()
) {}
static fromJSON(json: any): Tweet {
const rec = new Tweet(
json.text,
json.reacties,
json.created
);
return rec;
}
toJSON(): any {
return {
name: this.name,
reacties: this.reacties.map(re => re.toJSON()),
created: this.created
};
}
get name(): string {
return this._name;
}
get created(): Date {
return this._created;
}
get reacties(): Reactie[] {
return this._reacties;
}
addReactie(text: string) {
this._reacties.push(new Reactie(text));
}
}
数据服务
import { Injectable } from '@angular/core';
import { Observable, Subject, of } from 'rxjs';
import { map, catchError, tap } from 'rxjs/operators';
import { environment } from 'src/environments/environment';
import { HttpClient } from '@angular/common/http';
import { Tweet } from './tweet/tweet.model';
@Injectable({
providedIn: 'root'
})
export class TweetDataService {
public loadingError$ = new Subject<string>();
constructor(private http: HttpClient) {}
get recipes$(): Observable<Tweet[]> {
return this.http.get(`${environment.apiUrl}/Tweet/`).pipe(
catchError(error => {
this.loadingError$.next(error.statusText);
return of(null);
}),
map((list: any[]): Tweet[] => list.map(Tweet.fromJSON))
);
}
addNewTweet(tweet: Tweet) {
return this.http.post(`${environment.apiUrl}/tweets/`, tweet.toJSON());
}
getTweet$(id): Observable<Tweet> {
console.log(`${environment.apiUrl}/tweets/${id}`);
return this.http
.get(`${environment.apiUrl}/tweets/${id}`)
.pipe(map((rec: any): Tweet => Tweet.fromJSON(rec)));
}
}
答案 0 :(得分:0)
大多数情况下,由于服务的数据同步问题,导致此问题发生。
解决您的问题的简单方法是使用typesafe(?)
运算符,如下所示。
<mat-card>
<mat-card-header>
<mat-card-title>
{{ tweet?.name}}
</mat-card-title>
<mat-card-subtitle>added on {{ tweet?.created | date: longDate }}</mat-card-subtitle>
</mat-card-header>
</mat-card>
希望这会有所帮助!