【问题标题】:Argument of type date is not assignable to parameter of type string日期类型的参数不能分配给字符串类型的参数
【发布时间】:2019-07-29 19:24:52
【问题描述】:

我正在学习 Angular 和 .net 课程。

我正在尝试将 photourl 设置为方法。

我收到以下错误\

日期类型的参数不能分配给字符串类型的参数

错误在下一行。

this.changeMemberPhoto(this.currentUser.photoUrl);

论据是问题

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { BehaviorSubject } from 'rxjs';
import { map } from 'rxjs/operators';
import { JwtHelperService} from '@auth0/angular-jwt';
import { environment } from 'src/environments/environment';
import { User } from '../_models/user';

@Injectable({
  providedIn: 'root'
})

export class AuthService {
  baseUrl = environment.apiUrl + 'auth/';
  jwtHelpter = new JwtHelperService();
  decodedToken: any;
  currentUser: User;
  photoUrl = new BehaviorSubject<string>('../../assets/user.png');
  currentPhotoUrl = this.photoUrl.asObservable();

  constructor(private http: HttpClient) {}


  changeMemberPhoto(photoUrl: string) {
    this.photoUrl.next(photoUrl);
  }

  login(model: any) {
    return this.http.post(this.baseUrl + 'login', model).pipe(
      map((response: any) => {
        const user = response;
        if (user) {
          localStorage.setItem('token', user.token);
          localStorage.setItem('user', JSON.stringify(user.user));
          this.decodedToken = this.jwtHelpter.decodeToken(user.token);
          this.currentUser = user.user;
          this.changeMemberPhoto(this.currentUser.photoUrl);
        }
      })
    );
  }

  register(model: any) {
    return this.http.post(this.baseUrl + 'register', model);
  }

  loggedIn() {
    const token = localStorage.getItem('token');
    return !this.jwtHelpter.isTokenExpired(token);
  }
}

代码和导师一模一样,所以不知道是什么问题。

我已按要求包含了 User 类

import { Photo } from './photo';

export interface User {
    id: number;
    username: string;
    knownAs: string;
    age: number;
    gender: string;
    created: Date;
    lastActive: Date;
    photoUrl: Date;
    city: string;
    country: string;
    interests?: string;
    introduction?: string;
    lookingFor?: string;
    photos?: Photo[];
}

【问题讨论】:

  • 我看到了错误。用户类中的 PhotoURL 是一个日期。

标签: javascript angular typescript


【解决方案1】:

photoUrl 是您班级中的日期,是您的 changeMemberPhoto 方法中的字符串

在用户类中,将其更改为:

photoUrl: string;

【讨论】:

  • 我同意 Cyril 的观点,您的用户类将 photoUrl 设置为最新,但另一个文件将其用作字符串。也许在用户类中将 photoUrl: Date 更改为 photoUrl: String。
  • 我也同意 Cyril & Bobby 的观点。在 Typescript 中,类型对于方法或属性很重要。在您的 User 类中,您将 photoUrl 声明为 Date 类型。所以如果你想使用这个属性或者传递给它任何方法,那么它必须是相同类型的方法参数。由于您的命名模式 photoUrl 必须是字符串。因此,请让您的属性 photoUrl 类型为字符串,并且您的 BehaviorSubject 也接受字符串。所以你不能发出其他类型它也会显示错误。
猜你喜欢
  • 2017-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-21
  • 2021-10-13
  • 2018-06-24
  • 1970-01-01
相关资源
最近更新 更多