【发布时间】:2021-06-12 15:48:19
【问题描述】:
错误:键入“字符串 | null' 不可分配给类型 'string'。类型“null”不能分配给类型“string”。 错误:键入'{ id?:字符串|不明确的;标题?:字符串 |不明确的;内容?:字符串 |不明确的; }' 不可分配给类型 'Post'。 属性“id”的类型不兼容。 键入'字符串 | undefined' 不能分配给类型 'string'。 类型“未定义”不可分配给类型“字符串”。
export interface Post{
id:string;
title:string;
content:string;
}
import { Component,OnInit} from '@angular/core';
import { NgForm } from '@angular/forms';
import { ActivatedRoute, ParamMap } from '@angular/router';
import { Post } from '../post.model';
import { PostsService } from '../posts.service';
@Component({
selector: 'app-post-create',
templateUrl: './post-create.component.html',
styleUrls: ['./post-create.component.css']
})
export class PostCreateComponent implements OnInit {
// newPost='No Content'
enteredTitle=''
enteredContent=''
private mode='create'
private postId:string
private post:Post
// postId: string | null | undefined;
constructor(public postsService:PostsService
,public route: ActivatedRoute){}
ngOnInit(){
this.route.paramMap.subscribe((paramMap:ParamMap)=>{
if(paramMap.has('postId')){
this.mode='edit'
this.postId=paramMap.get('postId')
this.post=this.postsService.getPost(this.postId)
}else{
this.mode='create'
this.postId="null";
}
});
}
onAddPost(form:NgForm){
if(form.invalid)
{
return
}
console.log((form.value.title,form.value.content));
this.postsService.addPost(form.value.title,form.value.content)
form.resetForm();
}
}
【问题讨论】:
-
也许可以试试
private postId: string = '' -
你需要这个吗,this.postId="null"; , 你不能把它改成 ="";
-
@Grumpy this.postId=''null" 可以改为this.postId="" 但问题出在this.postId=paramMap.get('postId') this.post=this.postsService .getPost(this.postId)
-
@Emilien 不,这不是解决方案
-
使用前需要检查
if(postId)
标签: javascript node.js angular typescript